Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 135 ยท Arrays and Strings

Strings

Learn how C stores text - char arrays and the null terminator, string literals and why they are read-only, sizeof vs strlen, and printing and reading strings safely.

C has no string type. There's no string keyword, no built-in length, and no + to join two pieces of text. Instead, a string in C is a convention: a sequence of char values stored in an array and ended by a character with the value zero, written '\0'. Every function that works with text, from printf to the whole <string.h> library, relies on that terminator to know where the text stops.

This simple design is part of why C is fast and close to the machine, and also why string bugs are so common in C programs. In this lesson you'll learn how strings are stored, how string literals differ from character arrays, how to walk through a string with a loop, and how to print and read strings without overflowing anything. The next two lessons build on this: String Functions covers the standard library, and Safe String Handling covers defending against overflows.

Character arrays and the terminator

Here is a string being stored:

C
char word[] = "cat";

The compiler creates an array of four chars: the three letters and a terminating null character.

TEXT
index:    0      1      2      3
       +------+------+------+------+
       | 'c'  | 'a'  | 't'  | '\0' |
       +------+------+------+------+
value:    99     97    116     0

The null character '\0' is simply the char with numeric value 0. (Don't confuse it with '0', the digit character, whose value is 48 in ASCII, or with NULL, the null pointer.) Nothing stores the length of the string; functions find the end by scanning for that zero.

Two numbers describe a character array, and keeping them apart prevents a whole class of bugs:

  • sizeof word is the array's size in bytes: here 4, including the terminator and any unused space.
  • strlen(word) (from <string.h>) is the string's length: the number of characters before the first '\0', here 3.
C The null terminator up close

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints:

TEXT
word:    sizeof 4, strlen 3
name:    sizeof 16, strlen 3
spelled: "hi"
bytes of word: 99 97 116 0
cut:     "Barc" (strlen 4, sizeof still 10)
changed: bat

Look at the city line: putting a '\0' in the middle doesn't shrink the array, it just moves where every string function stops. The rest of the letters (lona) are still in memory, invisible.

The terminator also explains a rule you must follow every time you size a buffer: a string of n characters needs n + 1 bytes. A buffer for a 20-character name is char name[21]. Forgetting the extra byte is one of the most common C bugs.

A char array without a terminator is not a string. char letters[3] = {'a', 'b', 'c'}; is a perfectly good array, but passing it to printf("%s") or strlen is undefined behavior: they keep reading past the end until they happen to find a zero byte. The same trap exists with char code[3] = "abc";, which C allows: when the literal exactly fills the array, the terminator is silently dropped.

String literals

Text in double quotes, like "cat", is a string literal. The compiler stores it, with its terminator, in memory that exists for the whole run of the program. A literal can be used in two quite different ways:

C
char greeting[] = "hello";        // an ARRAY initialized with a copy of the text
const char *message = "hello";    // a POINTER to the literal itself

greeting is your own array of 6 bytes. You can change its contents freely. message is just an address (8 bytes on a 64-bit system) pointing at the literal's storage, which you must treat as read-only.

In C, a string literal technically has type char[N], not const char[N] (C++ made it const; C kept the old type for compatibility). So C lets you write char *p = "hello"; without complaint. But modifying a literal is undefined behavior, and on modern systems literals live in a read-only memory page, so a write like this crashes the program with a segmentation fault:

C
char *p = "hello";
p[0] = 'j';   // undefined behavior: usually a crash (SIGSEGV)

Always point at literals through const char *. Then the compiler stops you: p[0] = 'j' becomes a compile error instead of a crash. GCC's -Wwrite-strings flag goes further and gives literals a const type, so even char *p = "hello"; gets a warning.

C Arrays versus pointers to literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
jello / hello
sizeof greeting = 6 (the array)
sizeof message  = 8 (a pointer)
strlen of both  = 5 and 5
message now: goodbye
C strings are just char arrays
tab:	|  quote: "  backslash: \  newline next

Two handy facts from this example:

  • Adjacent literals are concatenated by the compiler, so you can split a long string across lines without any operator. This is the only "string joining" C does for free.
  • Escape sequences (\n, \t, \", \\, \0, \x41) let you put special characters inside a literal. Each one is a single char in the result. The Printing Output with printf lesson lists them all.

Walking through a string

Because a string ends at '\0', the natural loop runs until it reaches that character. This is how every string function is built, and writing a few yourself is the best way to understand them:

C Loops that walk a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints length: 16, vowels: 4, upper: PROGRAMMING IN C and reverse: C NI GNIMMARGORP.

Notice the details:

  • Functions that only read a string take const char *. Functions that change it take char *, and you must pass a modifiable array, never a literal.
  • A string parameter is a pointer (arrays decay, as you saw in Arrays), so the function doesn't need a length: it finds the end by itself. That's convenient, but it's also why a missing terminator is so dangerous.
  • to_upper walks with the pointer itself (s++) instead of an index. Both styles are common; Pointer Arithmetic explains the pointer version.
  • The <ctype.h> functions need their argument cast to unsigned char, because a plain char may be negative for non-ASCII bytes, which is undefined behavior for those functions. Characters and ASCII explains why.
  • Calling my_strlen once and saving the result is better than writing i < my_strlen(s) in a loop condition, which would rescan the string on every iteration.

Printing strings

printf prints a string with %s, which takes a pointer to the first character and prints until the terminator. Width and precision control the layout:

Format Effect Example with "Lisbon"
%s the whole string Lisbon
%10s right-aligned in 10 columns Lisbon
%-10s left-aligned in 10 columns Lisbon
%.3s at most 3 characters Lis
%.*s at most n characters, n passed as an int argument printf("%.*s", 2, s) โ†’ Li

Precision (%.3s) is also the safe way to print a char array that isn't terminated, as long as you know its length: printf reads no more than that many characters.

For plain output, puts(s) prints the string followed by a newline, and fputs(s, stdout) prints it without one. Never pass a string from input as the format argument (printf(user_text)): any % in it would be treated as a format specifier. Write printf("%s", user_text) or fputs(user_text, stdout).

Reading strings

Reading text into a fixed array is where most overflows begin, so learn the safe patterns from the start.

scanf("%s", buffer) reads one word (it stops at whitespace) and has no idea how big buffer is. A long word overflows it. If you use %s at all, always give a maximum width, which must be one less than the array size to leave room for the terminator: scanf("%19s", name) for char name[20].

fgets(buffer, size, stdin) reads a whole line, spaces included, and never writes more than size bytes, terminator included. It keeps the newline character at the end (if the line fit), so you usually strip it. This is the pattern to reach for:

C Reading words and lines safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
full name: "Grace Hopper"
surname:   "Lovelace"
piece 1:   "a line that is "
piece 2:   "much too long f"
piece 3:   "or the small bu"
piece 4:   "ffer"

Study the last part: when a line is longer than the buffer, fgets doesn't overflow and doesn't lose data. It fills the buffer with 15 characters plus '\0', and the next call continues where it stopped. If the newline is missing from what fgets returned, the line was cut (or the input ended). strcspn(line, "\n") returns the index of the first newline, or the length if there is none, so the stripping line is safe in both cases.

The old gets function, which read a line with no size limit at all, was so dangerous that C11 removed it from the language. You'll see why in Safe String Handling, along with how to handle input of any length.

Strings and character encodings

A char is one byte, and strlen counts bytes, not letters. For plain English text in ASCII that's the same thing. For other languages, text is usually stored in UTF-8, where characters outside ASCII take 2 to 4 bytes:

C
const char *word = "cafรฉ";
printf("%zu\n", strlen(word));   // 5: 'c' 'a' 'f' and two bytes for 'รฉ'

Printing UTF-8 strings with %s works as long as the terminal expects UTF-8 (ours does), but indexing word[3] gives you half a character. C11 added u8"..." literals that are guaranteed to be UTF-8, and C23 adds the char8_t type in <uchar.h> for them. Serious text processing (counting user-visible characters, changing case in all languages) needs a library such as ICU. For learning, keep in mind: in C, string length means bytes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are sizeof s and strlen(s) for char s[10] = "hey";?

    sizeof gives the size of the whole array (10 bytes). strlen counts the characters before the first '\0', which is 3.
  2. 2. What happens when this runs? char *p = "tea"; p[0] = 's';

    C accepts the declaration, but string literals must not be modified. They usually sit in read-only memory, so the write causes a segmentation fault. Use char p[] = "tea" for a modifiable copy, or const char * to point at a literal.
  3. 3. How many bytes does an array need to hold a string of 12 characters?

    Every string needs one extra byte for the terminating '\0', so 12 characters need 13 bytes.
  4. 4. After char t[] = "sunflower"; t[3] = '\0';, what does printf("%s", t) print?

    The terminator at index 3 ends the string after 's', 'u', 'n'. The remaining letters are still in the array, but printf stops at the first '\0'.
  5. 5. For char name[20], which call reads a word safely?

    The width counts characters, not bytes, so it must leave room for the terminator; 19 characters plus '\0' fill 20 bytes. %s has no limit, %20s can write 21 bytes, and gets no longer exists.

Summary

  • A C string is a char array whose text ends with the null character '\0'; nothing stores the length.
  • A string of n characters needs n + 1 bytes. A char array without a terminator is not a string.
  • sizeof gives the array's size; strlen counts characters (bytes) up to the terminator.
  • char a[] = "text" makes a modifiable copy; const char *p = "text" points at a read-only literal. Modifying a literal is undefined behavior.
  • Walk strings with a loop that stops at '\0'; take const char * for read-only parameters.
  • Print with %s (plus width and %.Ns precision), puts or fputs; never use input as a format string.
  • Read lines with fgets and strip the newline with strcspn; give scanf("%s") a width one less than the buffer size.
  • With UTF-8, one visible character can take several bytes.

Next: String Functions, a tour of <string.h> from strlen to strtok.