Why can you assign an array to a char pointer?

Usually, when you declare a pointer (e.g. int), you need to assign a memory address to it:

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

When you create a char pointer, you can assign it a char array without having to specify an address:

 char* c = "Char Array"; 

How it works? He allocates memory and points to this? Why can't other type pointers do the same?

+5
source share
2 answers

How it works?

The string literal is stored in a read-only data section in an executable file (this means that it is initialized at compile time) and c initialized to indicate that memory location. An implicit conversion between arrays and pointers handles the rest.

Note that converting string literals to char* is deprecated, because the content is readable anyway; prefer const char* when pointing to string literals.

Related construction char c[] = "Char Array"; will copy the contents of the string literal to the char array at runtime.

Why can't other type pointers do the same?

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

+7
source

Other type pointers can do this, and also just fine. A string literal is an array of characters, so you don't need to use an address operator to assign to a pointer.

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

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

char * simply determined that the literal type of a string is actually const char * , and it is still allowed to assign it (with a warning about failover).

+1
source

Source: https://habr.com/ru/post/1237466/


All Articles