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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With