First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Strings

Strings in C: char arrays with null terminator, literals, input/output, standard library functions, memory layout, and safe handling.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Strings represent text: sensor labels, file paths, user input, configuration, and protocol messages. Engineers often need to parse logs, validate inputs, and build formatted messages; understanding how C stores and manipulates strings is essential to write correct and safe programs.

Key ideas

  • String: A string in C is defined as "a finite sequence of characters terminated by the null character \0 and stored in contiguous memory." Assumptions: characters are stored in bytes, and the sentinel \0 marks the end. Consequence: the length of a C string is the count of bytes before the first \0.
  • Null terminator (\0): A special character with integer value 0 that ends the string. Without it, functions like printf("%s") and strlen will read past the intended end, causing undefined behavior.
  • String literal: A sequence of characters in double quotes, e.g., "Hello". It has static storage duration. Modifying a string literal results in undefined behavior; many implementations place literals in read-only memory. Use const char *p = "Hello"; to reflect that it should not be modified.
  • Character array vs. pointer to literal:
    • char a[] = "Hi"; creates a modifiable array: {'H','i','\0'}. You may change a[0] = 'h';.
    • char *p = "Hi"; points to a read-only literal; writing p[0] = 'h'; is undefined behavior.
  • String length vs. array size:
    • Length: Number of characters before \0, given by strlen(s). Does not count \0.
    • Size: Total storage allocated for the array, given by sizeof s when s is an array in scope. For char s[10] = "abc";, strlen(s) == 3, sizeof s == 10.
  • Initialization:
    • With literal: char s[] = "Hello"; // size 6 including '\0'
    • With characters: char t[6] = {'H','e','l','l','o','\0'};
    • Uninitialized arrays contain indeterminate values; always set or zero-initialize before use.
  • Indexing and iteration: Strings are arrays of char with indices from 0 up to length-1. Always stop at \0.
  • Input and output:
    • printf("%s", s) prints characters until \0.
    • scanf("%s", s) reads up to first whitespace; risky unless you limit width to avoid overflow.
    • fgets(s, n, stdin) reads up to n-1 chars or newline, stores \0, and keeps the newline if read. It is safer for lines with spaces.
    • gets was removed from the C standard due to insecurity; never use it.
    • puts(s) writes s then a newline.
  • Escape sequences: Special backslash forms inside character and string literals. Common ones: \n newline, \t tab, \\ backslash, \" double quote, \0 null character.
  • String library (string.h) — partial list:
    • strlen(s): length excluding \0.
    • strcpy(dst, src): copies src including \0 to dst; requires dst large enough.
    • strncpy(dst, src, n): copies up to n chars; does not guarantee \0 if src length ≥ n.
    • strcat(dst, src): appends src to end of dst; dst must have space.
    • strncat(dst, src, n): appends up to n chars; writes \0.
    • strcmp(a, b): lexicographic compare; returns <0, 0, >0.
    • strncmp(a, b, n): compares at most n chars.
    • strchr(s, c): pointer to first occurrence of c in s or NULL.
    • strstr(h, n): pointer to first occurrence of substring n in h or NULL.
    • strtok(s, delim): tokenizes s using delimiters; modifies input and is not thread-safe. On POSIX use strtok_r, and in C11 Annex K (if available) use strtok_s, for reentrant/thread-safe tokenization.
  • Character classification and case conversion (ctype.h): isalpha, isdigit, isspace, tolower, toupper. Rule: when passing a char to these macros, first cast to unsigned char (or use EOF) to avoid undefined behavior for negative char values.
  • Memory safety with strings:
    • Buffers must be large enough for content plus \0.
    • Prefer input limits: scanf("%49s", s), fgets(s, sizeof s, stdin).
    • Beware off-by-one errors when copying/appending.
    • strncpy truncation pitfalls: if truncation occurs, you may need to manually add \0.
    • snprintf safely formats into a buffer with size limit and always null-terminates (if size > 0).
  • Memory layout (diagram to draw in exam):
    • Draw a box row for char name[6] = "Hello";. Label indices 0..5. Write cells: index 0 'H', 1 'e', 2 'l', 3 'l', 4 'o', 5 '\0'. Draw an arrow labeling the base address &name[0]. Optionally, annotate that sizeof name = 6, strlen(name) = 5.
  • Definition of undefined behavior (for context): Program behavior for which the C standard imposes no requirements. Examples here: reading a string without \0, writing into string literals, overrunning buffers.

Formulas

  • char s[6] = "Hello";
  • char t[] = "abc"; // size becomes 4 including '\0'
  • const char *p = "Read-only literal";
  • Basic I/O with strings
    • printf("%s", s);
    • scanf("%49s", s); // reads a word, limits to 49 chars + '\0'
    • fgets(s, sizeof s, stdin); // reads a line incl. spaces, keeps '\n' if room
    • puts(s); // prints s and a newline
  • Common library functions (string.h)
    • size_t strlen(const char *s);
    • char *strcpy(char *dst, const char *src);
    • char *strncpy(char *dst, const char *src, size_t n);
    • char *strcat(char *dst, const char *src);
    • char *strncat(char *dst, const char *src, size_t n);
    • int strcmp(const char *a, const char *b);
    • int strncmp(const char *a, const char *b, size_t n);
    • char *strchr(const char *s, int c);
    • char *strstr(const char *haystack, const char *needle);
    • char *strtok(char *str, const char *delim);
  • Character classification (ctype.h)
    • int isalpha(int c); int isdigit(int c); int isspace(int c);
    • int tolower(int c); int toupper(int c);
    • Usage note: if (isalpha((unsigned char)ch)) { ... }
  • Safe formatting
    • int snprintf(char *dst, size_t size, const char *fmt, ...);
  • Escape sequences in literals
    • "Line1\nLine2", "Tab\tSeparated", "Quote: \"", "Backslash: \\", "Null: \0"

Worked examples

Example 1 — Read a full line and count characters, digits, vowels, and words Program:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

int main(void) {
    char line[256];
    if (!fgets(line, sizeof line, stdin)) {
        return 0; // no input
    }

    // Remove trailing newline if present
    size_t len = strlen(line);
    if (len > 0 && line[len - 1] == '\n') {
        line[len - 1] = '\0';
        len--; // length excluding newline
    }

    int vowels = 0, digits = 0, words = 0;
    bool in_word = false;

    for (size_t i = 0; line[i] != '\0'; i++) {
        unsigned char ch = (unsigned char)line[i];
        char lower = (char)tolower(ch);
        if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
            vowels++;
        }
        if (isdigit(ch)) {
            digits++;
        }
        if (!isspace(ch)) {
            if (!in_word) {
                in_word = true;
                words++;
            }
        } else {
            in_word = false;
        }
    }

    printf("Characters (excluding newline): %zu\n", len);
    printf("Vowels: %d\n", vowels);
    printf("Digits: %d\n", digits);
    printf("Words: %d\n", words);
    return 0;
}

Sample input:

Hello India 2025!

Exact output:

Characters (excluding newline): 17
Vowels: 5
Digits: 4
Words: 3

Example 2 — Reverse a string in place (line with spaces) Program:

#include <stdio.h>
#include <string.h>

void reverse(char *s) {
    size_t i = 0, j = strlen(s);
    if (j == 0) return;
    j--; // last character index
    while (i < j) {
        char tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
        i++;
        j--;
    }
}

int main(void) {
    char s[128];
    if (!fgets(s, sizeof s, stdin)) return 0;
    size_t len = strlen(s);
    if (len > 0 && s[len - 1] == '\n') {
        s[len - 1] = '\0';
    }
    printf("Original: %s\n", s);
    reverse(s);
    printf("Reversed: %s\n", s);
    return 0;
}

Sample input:

Programming in C

Exact output:

Original: Programming in C
Reversed: C ni gnimmargorP

Example 3 — Safe concatenation of first and last name with space Program:

#include <stdio.h>

int main(void) {
    char first[50], last[50];
    char full[101];

    // Read first and last names as single words (no spaces inside)
    if (scanf("%49s %49s", first, last) != 2) {
        return 0;
    }

    // Safely format into full name buffer
    // Ensures null-termination and avoids overflow
    int n = snprintf(full, sizeof full, "%s %s", first, last);
    if (n < 0 || n >= (int)sizeof full) {
        // Truncation occurred or formatting error
        // In real programs, handle appropriately
    }

    printf("Full name: %s\n", full);
    return 0;
}

Sample input:

Asha Verma

Exact output:

Full name: Asha Verma

Common mistakes

  • Using gets or scanf("%s", s) without a width limit, causing buffer overflow on long inputs.
  • Confusing strlen with sizeof: writing code that assumes sizeof s equals string length when s is not a fixed array (e.g., when s is char *).
  • Trying to modify string literals via char *p = "Hi"; p[0] = 'h'; — undefined behavior.
  • Comparing strings with == instead of strcmp; == only compares pointer addresses, not content.
  • Off-by-one errors in loops and copying, such as copying exactly n visible characters but forgetting to leave space for \0.
  • Misusing strncpy: assuming it always appends \0. If truncation happens, the destination may not be terminated.
  • Not handling the trailing newline from fgets, leading to unexpected extra \n in strings.
  • Passing a plain char with a negative value to isalpha/tolower without casting to unsigned char, causing undefined behavior on some platforms.
  • Using strtok on a string literal or using it in multi-threaded contexts without care; it modifies the input and keeps internal state.

For your exam

  • Short notes: Differences between char[] and char *, strlen vs. sizeof, safe input methods (fgets, width-limited scanf), and common string functions (strcpy, strcat, strcmp). Include function prototypes and mention headers (string.h, ctype.h).
  • Programs: Typical tasks include counting characters/digits/words, reversing a string, concatenating names, comparing two strings lexicographically, searching for a substring, or validating that a string is numeric. Use safe I/O, show correct headers, and handle \n from fgets.
  • Diagrams: Memory layout of a string array with indices and \0. Label strlen and sizeof results.
  • Best practices to mention: input bounds, always keep space for \0, avoid modifying string literals, cast to unsigned char for ctype.h functions, prefer snprintf for formatting.
  • Marks come from: correct syntax, inclusion of headers, proper termination handling, correct algorithmic logic, and clean, readable output matching the sample format.

Quick check

  1. Define a C string and explain the role of the null terminator.
  2. What is the difference between strlen(s) and sizeof s when s is declared as char s[20] = "Hi";?
  3. Write the safest single line to read a word (no spaces) of up to 49 characters into char buf[50]; using scanf.

Answers: 1) A C string is a sequence of char values stored contiguously and terminated by the null character \0; \0 marks the end for all string functions. 2) strlen(s) is 2 (number of visible characters), while sizeof s is 20 (total bytes allocated for the array). 3) scanf("%49s", buf);

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?