Character Strings
Unlike Python or Java, C does not have a built-in String data type. Instead, a string is simply a 1-D array of characters, terminated by a special invisible null character \0.
"HELLO"?Array of Characters
Under the hood, strings use the char data type (1 byte per character).
Null Terminator
Every string must end with the null character \0 (ASCII value 0) so C knows where it stops.
Double Quotes
Strings are enclosed in " ", while single characters are enclosed in ' '.
Format Specifier
Use %s in printf and scanf to read or write an entire string.
Declaration & Initialization
You can initialize strings character-by-character (tedious) or using a string literal shortcut. Both achieve the same memory layout.
Memory Layout & The Null Terminator \0
Arrays in C don't store their own length. The only way C functions like printf know when to stop printing a string is by looking for the Null Terminator (\0).
Interactive Memory Visualizer
Type a word below to see how it's stored in a 10-byte character array:
char str[10] = "HELLO";Reading & Writing Strings
To read a string, use scanf or fgets. Be careful: scanf("%s") stops reading at the first space!
scanf("%s", str);
Reads characters until it encounters a whitespace (space, tab, or newline). Note: No `&` before `str` because an array name is already an address!
fgets(str, size, stdin);
Safely reads a full line of text, including spaces, up to `size - 1` characters. Recommended for reading sentences.
Simulation: scanf vs fgets
Common <string.h> Functions
C provides the <string.h> library containing powerful utility functions to manipulate strings without manually writing loops.
strlen(str)
Returns the length of the string (excluding the null terminator).
strcpy(dest, src)
Copies the contents of string `src` into `dest`. Overwrites `dest`.
strcmp(str1, str2)
Compares two strings. Returns 0 if they are exactly identical.