Arrays & Strings · beginner · ~8 min

Character arrays

Distinguish a char buffer from a NUL-terminated string.

Lesson

char is just a small integer (1 byte). char buf[16] is 16 such bytes. A string is a char array whose contents end in a \0 (zero byte) byte — that's the convention every standard library function expects.

String literals like "hello" have type char[6] (5 visible chars + the NUL). They live in read-only memory; assigning into them is undefined behaviour.

Code examples

char buf[16] = "hi";   // 'h','i','\0', rest zero
buf[2] = '!';          // ok — buf is writable
buf[2] = '\0';         // truncate to "hi"

Common mistakes

  • Confusing 'a' (a single char) with "a" (a 2-byte string).
  • Writing into a string literal: char *p = "hi"; p[0] = 'H'; crashes.