Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
Daniel Avatar asked Dec 05 '15 16:12

Daniel


2 Answers

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.

like image 89
emlai Avatar answered Oct 27 '22 00:10

emlai


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).

like image 22
EmDroid Avatar answered Oct 27 '22 01:10

EmDroid