Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a char pointer C++ [duplicate]

Tags:

c++

char

pointers

How is this even possible?

const char *cp = "Hello world";

I am currently reading C++ primer and i found this example (I am a very beginner).

Why is it possible to initialize a char pointer with a string? I really can't understand this example, as far as I know a pointer can only be initialized with & + the address of the object pointed OR dereferenced and THEN assigned some value.

like image 832
Federico Nada Avatar asked Aug 02 '17 09:08

Federico Nada


1 Answers

String literals are really arrays of constant characters (with the including terminator).

When you do

const char *cp = "Hello world";

you make cp point to the first character of that array.


A little more explanation: Arrays (not just C-style strings using arrays of char but all arrays) naturally decays to pointers to their first element.

Example

char array[] = "Hello world";  // An array of 12 characters (including terminator)
char *pointer1 = &array[0];  // Makes pointer1 point to the first element of array
char *pointer2 = array;  // Makes pointer2 point to the first element of array

Using an array is the same as getting a pointer to its first element, so in fact there is an address-of operator & involved, but it's implied and not used explicitly.

As some of you might have noted, when declaring cp above I used const char * as the type, and in my array-example with pointer1 and pointer2 I used a non-constant plain char * type. The difference is that the array created by the compiler for string literals are constant in C++, they can not be modified. Attempting to do so will lead to undefined behavior. In contrast the array I created in my latter example is not constant, it's modifiable and therefore the pointers to it need not be const.

like image 162
Some programmer dude Avatar answered Oct 27 '22 05:10

Some programmer dude