Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Strings

Continued String Literal

When two or more string literals are adjacent (separated only by whitespace), the compiler will join them into a single string. Examples:

printf("All "
       "of "
       "this will be "
       "printed on one line\n");

Format specifiers can be used that way too.

How String Literals Are Stored

String literal is an array of characters. When compiler finds a string literal of length n, it reserves n + 1 bytes of memory for the string. Null character (byte with all bits set to 0) - \0 - will be added to it to mark the end of string. Since it is stored as an array, compiler treats it as a pointer of type char *.

When declaring an array of characters always make the array one character longer to accomodate for null character which is expected by compiler. If character array has less elements than declared, the length of the string depends on the position of the null character not on the length of the array.

Modifying String Literal

Attempting to modify a string literal causes undefined behavior.

Initializing a String Variable

char str[6] = "Hello";

Compiler will adds null character at the end. "Hello" in this case is not a string literal, C treats it as an array of characters.

If initializer is too short to fill in the array, e.g.

char str[10] = "Hello";

Compiler will fill in the rest of the array with 0's that is with null character.

If initializer is exactly of the same length as the variable, compiler will allow it and no null character will be added. In this case the array will be unusable as a string though.

Finally, length can be omitted, then compiler will compute the length of the array. This does not mean that the length of the array can be changed later!

Character Arrays vs Character Pointers

TypeDeclarationSpecifics
Character Arraychar str[]- Can pass it to a function that expects either pointer or an array
- Elements of array can be modified
- str is the name of an array
Character Pointerchar *str = "Some String"- Can pass it to a function that expects either pointer or an array
- Points to string literal which cannot be modified
- Can point to other strings during execution