Strings
Challenge Gallery
Quick Reference
String declaration patterns:
| Pattern | Modifiable? | Storage |
|---|---|---|
char s[] = "hello"; |
Yes | Stack (copy) |
char *s = "hello"; |
No | Read-only literal |
char s[10] = "hello"; |
Yes | Stack, 10 bytes |
Essential string functions (from <string.h>):
strlen(s) // Length (not counting '\0')
strcmp(s1, s2) // Compare: 0 = equal
strcpy(dest, src) // Copy (unsafe — no bounds check)
strncpy(dest, src, n) // Copy at most n chars
strcat(dest, src) // Append src to dest
Common Pitfalls
- Forgetting null terminator – A “string” without ‘\0’ causes functions to read past the array.
- Using == to compare – Compares addresses, not contents. Use
strcmp. - Writing to literals –
char *s = "hi"; s[0] = 'H';is undefined behavior. Usechar s[]. - Buffer overflow with strcpy – Always ensure destination is large enough.
- strlen vs sizeof –
strlen("hi")is 2,sizeof("hi")is 3 (includes ‘\0’).