What is the difference between char *s = "hello" and char s[] = "hello"?
Short answer: char *s = "hello"; makes s a pointer to a string literal, which usually lives in read-only memory (.rodata, often flash on an MCU); modifying it is undefined behaviour. char s[] = "hello"; creates a writable array of 6 chars (including '\0') initialised with a copy of the literal.
char *p = "hello"; /* pointer (4 or 8 bytes) to a literal in .rodata */
char a[] = "hello"; /* 6-byte array (on the stack if local, .data if global) */
a[0] = 'H'; /* fine */
p[0] = 'H'; /* undefined: may crash (Linux: SIGSEGV), or be ignored (flash) */
sizeof p; /* 4 or 8 */
sizeof a; /* 6 */
strlen(a); /* 5 */
p = "world"; /* fine: point somewhere else */
a = "world"; /* error: arrays cannot be assigned */
Best practice: declare pointers to literals as const char *p = "hello"; so the compiler rejects writes. GCC's -Wwrite-strings makes string literals const char[] to catch this. In C++, a literal already has type const char[N].
Memory layout consequences on a microcontroller
| Declaration | Flash | RAM |
|---|---|---|
const char *msg = "hello"; (global) |
6 bytes (literal) | 4 bytes (the pointer, in .data) |
const char *const msg = "hello"; (global) |
6 + 4 bytes | 0 |
char msg[] = "hello"; (global) |
6 bytes (initial value) | 6 bytes (.data) |
static const char msg[] = "hello"; |
6 bytes | 0 |
char msg[] = "hello"; (local) |
6 bytes (initial value) + copy code | 6 bytes of stack each call |
For constant strings in firmware, static const char msg[] = "..." uses no RAM at all.
Identical literals may share storage: "hello" == "hello" may be true or false; the compiler is allowed to merge them. Compare strings with strcmp, never with ==.