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

String literals as `char` pointers

String literals as char pointers

What you'll learn: Understand how C treats text inside double quotes as a memory address rather than just a collection of letters.

The Secret Address

When you write a string like "Hello" in C, you aren't just writing text; you are creating a hidden array in a special "read-only" part of your computer's memory. The C compiler sees that string and says, "I'll store these characters in a safe spot and give you the memory address of the very first letter."

Think of a string literal like a house in a neighborhood. The string "Hello" is the physical house, but in your code, the literal itself acts like a GPS coordinate pointing to the front door.

Assigning Strings to Pointers

Because a string literal evaluates to a memory address, we can store that address directly in a char * (a pointer to a character). Unlike an array, which reserves its own space, a pointer simply "points" to the pre-existing space where the literal is stored.

#include <stdio.h>

int main() {
    // The pointer 'message' stores the address of the 'H'
    char *message = "C is powerful";

    // We can print it normally
    printf("%s\n", message);

    // We can even point to a different literal later
    message = "New direction";
    printf("%s\n", message);

    return 0;
}

Look, but Don't Touch

There is one major rule when using pointers with string literals: You cannot change the characters.

When you use char *message = "Hello";, the characters are stored in a read-only segment of memory. If you try to do something like message[0] = 'B'; to turn "Hello" into "Bello," your program will likely crash (a "Segmentation Fault").

Imagine the string literal is a sign behind a glass display at a museum. You can read it, you can take a picture of it, and you can tell people where it is located, but if you try to reach through the glass to erase a letter, the alarm will go off. If you need to modify text, you should use a char array instead.

Key takeaway

A string literal is a pointer to a constant, read-only sequence of characters stored in memory.