Nearby lessons
65 of 124C - String Initialization
All the ways to initialise a string in C — string literals, character lists, letting the compiler size the array, and using strcpy to assign text after declaration.
Method 1 — String Literal (Preferred)
Assign a quoted string at the point of declaration. The compiler appends '\0' automatically:
Method 2 — Character List
List each character individually. Here you must supply the terminator — the compiler will not add it:
What Fills the Spare Bytes?
When you declare a larger array than the text needs, every remaining byte is set to '\0' — not left as garbage:
Initialising an Empty String
An "empty" string is one whose first byte is already the terminator. All three forms below are equivalent:
After Declaration — Use strcpy
The literal form works only at declaration. Later on, = is illegal and you must copy:
Building a String Character by Character
If you fill an array manually, remember to place the terminator yourself when you are done:
Safe Copying with strncpy
strcpy does not check the destination size. strncpy takes a limit — but note that it does not always terminate, so add the \0 yourself:
Common Mistakes
| Mistake | Problem |
|---|---|
char s[5] = "Hello"; | No room for \0 |
{'H','i'} without '\0' | Not a valid string |
s = "text"; after declaring | Arrays are not assignable |
strcpy into a too-small array | Buffer overflow |
Filling manually and forgetting \0 | printf reads past the end |
char *s; strcpy(s, "Hi"); | Writes through an uninitialised pointer |
char s[5] = "Hello"; is especially nasty. Some compilers accept it with only a warning, storing the 5 letters and dropping the terminator. The program then appears to work until printf happens to run into a non-zero byte. Always count the terminator.- char s[] = "Hello"; is the simplest form — \0 is added for you.
- A character list needs \0 written explicitly.
- Unused bytes in a partially initialised array become \0.
- After declaration you must use strcpy, not =.
- char s[] = "Hi" sizes the array to 3 automatically.