papercut
papercut

Reputation: 51

What exactly does a char* mean in C++?

My understanding is that it is meant to contain the memory address of a char variable, but now I'm seeing it can be used to create strings? For example,

char* ptr = "string";

How can ptr be assigned a string when it is meant to hold a memory address? I thought the dereference operator would be needed to change the value being pointed to?

Upvotes: 5

Views: 6702

Answers (2)

Miles Budnek
Miles Budnek

Reputation: 30694

Your understanding is correct; a char* does point to a single char.

The trick is that arrays are laid out contiguously in memory, so given a pointer to the first element of an array, you can access the other elements by simply adding an offset to the pointer. In your example, things look (logically) like this:

+-----+
| ptr |
+--+--+
   |
   v
 +-+-+---+---+---+---+---+----+
 | s | t | r | i | n | g | \0 |
 +---+---+---+---+---+---+----+

ptr points at the 's' at the beginning of "string". By adding 1 to ptr, you can find the 't', and so on. That's what the (builtin) [] operator does. ptr[2] is defined to be equvilent to *(ptr + 2): offset the pointer by 2 positions, and then fetch the value pointed to by the result.

A '\0' character is used to mark the end of the string, so that the consuming code knows to stop looking for more characters.

Upvotes: 7

Bathsheba
Bathsheba

Reputation: 234875

"string" is a const char[7] type literal. C++ allows you to use the rabbits ears to simplify the language. The 0 terminator is added for you, which is why there are 7 elements, not 6.

In various instances, array types decay to pointer types, with the pointer set to the first element of the array. Assignment is one of those instances. And that's what is happening here.

Formally, from C++11 onwards, your C++ compiler should not compile that statement. It should be

const char* ptr = "string";

Upvotes: 12

Related Questions