Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 2: Strings, Storage & Scope
C

Part 2: Strings, Storage & Scope

Understand character arrays, string literals, string functions, storage classes, variable scope, and object lifetimes in C.

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: sizeof the whole string for s[] vs pointer size for p.
char s[] = "hi";    // {'h','i','\0'}
printf("%zu %zu\n", sizeof s, sizeof "hi");   // 3 3

2. Standard string functions

FunctionBehaviour
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 / strstrfind char / substring, returns pointer
  • Safety-first recommendation in interviews: strncpy vs snprintf correctness (“snprintf is the safer string builder”).

3. Storage classes — the lifecycle

ClassLifespanScopeDefault value
autoblockblockgarbage
registerblockblockhint to register / garbage
static localwhole programblockzero
static global / funcwhole programfilezero
externwhole programlink to another fileshared
constmodifies type “read-only”as its var
  • static inside a function: value persists across calls, initialized once to zero.
  • extern extends 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.
  • strlen vs sizeof; string function bounds.
  • Storage classes: static inside file vs function.
  • Const pointer forms.
  • Lifecycle vs scope: static initialization happens exactly once, at first/load time.

My Private Notes

Notes are auto-saved locally to this device.