Nearby lessons
64 of 124C - String Declaration
How to declare a string in C — a fixed-size char array versus a char * pointer to a string literal, and the crucial difference in whether the contents can be modified.
Form 1 — The char Array
This reserves a block of writable bytes that you own. It is the form to use whenever the text will change:
Form 2 — The char Pointer
A char * holds the address of text. When it points at a string literal, that text usually lives in a read-only section of the program:
The Critical Difference — Modifiability
You can change the characters of an array. You must not change the characters of a string literal, even through a pointer:
Why the Pointer Version Crashes
char arr[] = "Hello"; copies the text into your array — you own it, so you can edit it. char *ptr = "Hello"; does not copy anything; it just records where the compiler's literal lives. That memory is typically marked read-only, so writing to it triggers a segmentation fault.Because the mistake is so easy to make, always write const char * when you only intend to read. Then the compiler catches the error instead of your users:
Array vs Pointer — Side by Side
char s[] = "Hi"; | char *s = "Hi"; | |
|---|---|---|
| What is stored | A writable copy of the text | An address only |
| Memory location | Stack (if local) | Read-only data section |
sizeof(s) | 3 (text + \0) | 8 (pointer size) |
| Modify characters | Yes | No — undefined behaviour |
| Repoint to other text | No | Yes |
| Best for | Buffers you will edit | Fixed messages you only read |
Sizing the Array Correctly
Always reserve one byte more than the longest text you expect:
An Array of Strings
To hold several strings you need a 2D char array, or an array of pointers:
Common Mistakes
- Modifying a string literal —
char *s = "Hi"; s[0] = 'B';crashes at runtime. - Forgetting the terminator's byte —
char s[5] = "Hello";has no room for\0. - Using
sizeofon achar *— gives 8, the pointer size, not the text length. - Copying into an uninitialised pointer —
char *s; strcpy(s, "Hi");writes to a random address. - Returning a local array from a function — the memory is gone once the function returns.
char s[] gives you your own writable copy; char *s gives you a view of someone else's constant. Adding const to the pointer form turns a runtime crash into a compile-time error.- char s[50]; reserves 50 writable bytes.
- char *s = "text"; points at a read-only string literal.
- Array form: modifiable. Pointer-to-literal form: do not modify.
- Always leave room for the \0 when sizing an array.
- Use const char * when you only need to read the string.