Get In The Shell
Get In The Shell

Reputation: 65

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?

Upvotes: 5

Views: 998

Answers (2)

EmDroid
EmDroid

Reputation: 6066

Other type pointers can do this as well just fine. A string literal is array of chars, so you don't need to use address operator to assign to pointer.

If you have an integer array, either int * or int[] you can assign it to int pointer without using the address operator as well:

int intArray1[] = {0, 1, 2}; // fist array
int * intArray2 = new int[10]; // second array
// can assign without & operator
int * p1 = intArray1;
int * p2 = intArray2;

The char * is just specific that the string literal type is actually const char * and is is still allowed to assign (with a warning about deprecated conversion).

Upvotes: 1

Emil Laine
Emil Laine

Reputation: 42828

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.

Upvotes: 7

Related Questions