Search code examples
c++arrayspointersstring-literals

Why can you assign an array to a char pointer?


Usually when you declare a pointer (such as an int) you'd have to assign a memory address to it:

int value = 123;
int* p = &value;

When you create a char pointer, you can assign a char array to it without the need of including an address:

char* c = "Char Array";

How does this work? Does it allocate memory and point to that? Why can't other type pointers do the same thing?


Solution

  • How does this work?

    The string literal is stored in a read-only data section in the executable file (meaning it is initialized during compilation) and c is initialized to point to that memory location. The implicit array-to-pointer conversion handles the rest.

    Note that the conversion of string literals to char* is deprecated because the contents are read-only anyway; prefer const char* when pointing to string literals.

    A related construct, char c[] = "Char Array";, would copy the contents of the string literal to the char array at runtime.

    Why can't other type pointers do the same thing?

    This is a special case for string literals, for convenience, inherited from C.