Mutable vs immutable string memory
What you'll learn: Why the way you declare a string determines whether you are allowed to change its characters later.
In C, there are two common ways to create a string, and they look almost identical. However, under the hood, they place your data in very different parts of the computer's memory.
The "Array" (A Sketchbook)
When you declare a string as an array, like char myStr[] = "Hello";, C treats it as a local variable. It allocates space on the "stack"—a part of memory your program owns and can rewrite.
Think of this like writing in a sketchbook. You wrote "Hello" in pencil. If you want to change the 'H' to a 'J', you can simply erase and overwrite it. The memory is yours to modify.
The "Pointer" (A Printed Book)
When you declare a string using a pointer, like char *myStr = "Hello";, something different happens. C stores the characters "Hello" in a special, read-only section of memory called the Data Segment. Your pointer just points to that location.
Think of this like a printed book. You can see the word "Hello" on the page, but you aren't allowed to change it. If you try to force a change, the program will crash (usually with a "Segmentation Fault") because you are trying to write to a "read-only" zone.
Code Example
See the difference in action below:
#include <stdio.h>
int main() {
// 1. MUTABLE: This is an array. We can change it.
char mutableStr[] = "Hello";
mutableStr[0] = 'J';
printf("%s\n", mutableStr); // Prints "Jello"
// 2. IMMUTABLE: This is a pointer to a string literal.
// The characters live in read-only memory.
char *immutableStr = "Hello";
// The following line would cause a crash/error:
// immutableStr[0] = 'J';
return 0;
}
Why does this matter?
Using the pointer method (char *) is memory-efficient because the computer can reuse that same "Hello" elsewhere, but it is dangerous if you plan to edit the text. If you need to change the content of your string during the program, always use the array syntax (char[]).
Key takeaway
String literals assigned to pointers are read-only (immutable), while strings stored in arrays are modifiable (mutable).