Course contentsShow
← C
Lesson 484 of 1,2197. PointersFree lesson

Memory layout of string pointers

Memory layout of string pointers

What you'll learn: You will understand how a string pointer differs from a character array by visualizing where their data lives in your computer's memory.

The "Signpost" vs. the "House"

In C, when you create a string using an array like char myName[] = "Alice";, you are building a house. The letters 'A', 'l', 'i', 'c', 'e', and the null terminator \0 are physically stored inside that array’s memory space. You own that space, and you can change the furniture (the letters) whenever you like.

However, when you create a string pointer like char *myPtr = "Alice";, the behavior changes. Instead of building a house, you have created a signpost. The actual text "Alice" is stored in a special, read-only neighborhood of your computer's memory called the Data Segment. Your pointer myPtr simply holds the address of that distant neighborhood.

Visualizing the Layout

Think of the pointer as a remote control. The control is in your hand (the Stack), but the TV it controls is bolted to the floor in a showroom (Read-Only Memory).

#include <stdio.h>

int main() {
    // This is an array: the data is local and changeable.
    char arrayStr[] = "Hello"; 

    // This is a pointer: it points to a constant string literal.
    char *ptrStr = "Hello";    

    // Both look the same when printed...
    printf("%s\n", arrayStr);
    printf("%s\n", ptrStr);

    // BUT: arrayStr[0] = 'J'; is fine.
    // ptrStr[0] = 'J'; // This would likely CRASH the program!
    
    return 0;
}

Why does this matter?

When you use a pointer to point to a string literal like "Hello", C treats that string as a constant. Because the pointer just holds an address to a "read-only" zone, trying to modify a character through that pointer (like changing 'H' to 'J') is a common cause of program crashes.

The array version copies the letters into its own workspace, making it safe to edit. The pointer version just "borrows" a look at a fixed piece of memory.

Key takeaway

A string array stores the actual characters in its own memory, while a string pointer only stores the address of a read-only string located elsewhere.