student@ubuntu:~$
c 3/5 30 XP

Strings

0%

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 literalschar *s = "hi"; s[0] = 'H'; is undefined behavior. Use char s[].
  • Buffer overflow with strcpy – Always ensure destination is large enough.
  • strlen vs sizeofstrlen("hi") is 2, sizeof("hi") is 3 (includes ‘\0’).

Unlocks

Complete this skill to see what it unlocks.