9

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.

Federico Nada
  • 109
  • 1
  • 1
  • 3

3 Answers3

13

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
5

"Hello world" is a read-only literal with a const char[12] type. Note that the final element is the NUL-terminator \0 which the language exploits as an "end of string" marker. C and C++ allow you to type a literal using " surrounding the alphanumeric characters for convenience and that NUL-terminator is added for you.

You are allowed to assign a const char[12] type to a const char* type by a mechanism called pointer decay.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

pointer can only be initialized with & + the address of the object pointed

int i = 0;
int *pointer = &i;

It's correct but it not the only way to initialized pointers. Look at below exmaple.

int *pointer;
pointer = (int*)malloc(100 * sizeof(int));

It is how you initialized pointers by allocating memory to it.

How is this even possible?

It works because "Hello World" is a string constant. You do not need to allocate this memory, it's the compiler's job.

By the way, always use smart pointer instead of raw pointer if you're using c++.

Shiu Chun Ming
  • 227
  • 2
  • 13