1. Strings: arrays vs literals
char s[] = "hi";— writable array, size from literal (len+1 for\0).char *p = "hi";— pointer into a string literal, usually read-only; writing is UB.- Difference:
sizeofthe whole string fors[]vs pointer size forp.
char s[] = "hi"; // {'h','i','\0'}
printf("%zu %zu\n", sizeof s, sizeof "hi"); // 3 3
2. Standard string functions
| Function | Behaviour |
|---|---|
strlen(s) | length, O(n), not the size + 1 |
strcmp(a, b) | 0 if equal, <0/>0 if a<b/a>b — byte order |
strcpy(d, s) | copy s to d, no bounds → overflow risk |
strncpy(d, s, n) | bounded, may not null-terminate |
strcat(d, s) | append, no bounds → overflow risk |
strchr / strstr | find char / substring, returns pointer |
- Safety-first recommendation in interviews:
strncpyvssnprintfcorrectness (“snprintf is the safer string builder”).
3. Storage classes — the lifecycle
| Class | Lifespan | Scope | Default value |
|---|---|---|---|
auto | block | block | garbage |
register | block | block | hint to register / garbage |
static local | whole program | block | zero |
static global / func | whole program | file | zero |
extern | whole program | link to another file | shared |
const | — | modifies type “read-only” | as its var |
staticinside a function: value persists across calls, initialized once to zero.externextends visibility across files.
4. const, volatile, and qualifiers
const int x = ...— cannot modify; still requires initialization.const int *p— pointer to const int (can move, can’t write through p).int * const p— const pointer to int (can write through p, can’t re-point).volatile— tell compiler the variable changes out-of-band (hardware, signal handlers).
5. Interview checkpoint
- Array of char vs string literal — modification and lifetime.
strlenvssizeof; string function bounds.- Storage classes:
staticinside file vs function. - Const pointer forms.
- Lifecycle vs scope: static initialization happens exactly once, at first/load time.
Premium Content
Unlock Part 2: Strings, Storage & Scope and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans