c language · high

C: String Literals — char* vs char[]

A C string literal such as "hello" is an array of char with static storage duration, normally placed in a read-only section (.rodata) and possibly merged with identical literals. char* p = "hello"; makes p point at that shared read-only storage, so writing through it (p[0] = 'H') is undefined behavior and usually crashes — prefer const char* for literals. By contrast, char a[] = "hello"; declares an array and copies the literal's bytes into your own writable storage (6 bytes including the terminator, on the stack for a local), so a[0] = 'H' is fine. The rule of thumb: use an array when you intend to modify the string and const char* when it is constant. A literal includes its trailing '\0', so sizeof("hello") is 6 (and has array type, giving the full byte size), whereas sizeof on a char* yields pointer size; strlen counts only up to the terminator. Finally, adjacent string literals are concatenated at compile time, so "ab" "cd" becomes "abcd".

🔑 Key line

C string literals are static read-only arrays (incl '\0'): char* p=".." points at .rodata so writing is UB, while char a[]=".." copies into writable storage; sizeof a literal counts the terminator, adjacent literals concatenate.

The code

char* p = "hello"; // p -> read-only literal in .rodata
p[0] = 'H'; // UNDEFINED BEHAVIOR (often a crash)
char a[] = "hello"; // a is a 6-byte COPY on the stack
a[0] = 'H'; // fine: modifying your own array
sizeof("hello") // 6 (5 chars + '\0'), an array type
"ab" "cd" // adjacent literals concatenate -> "abcd"

What this lesson walks through

  1. 01A string literal lives in read-only memory
  2. 02char[] makes a writable COPY on the stack
  3. 03Gotcha — writing to a literal is UB
  4. 04sizeof, the terminator, and concatenation

char* p = "hello" makes p point at a literal stored in the read-only .rodata segment. You may read it, but the bytes are shared and immutable.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of C: String Literals — char* vs char[] and 100+ animated C++ interview lessons.

← Previous
C++20 consteval & constinit — Compile-Time Guarantees
Next →
C: Pointers vs Arrays (Decay)