char* doesn't hold the memory address

Viewed 417

I have been teaching myself C and C++ and am somewhat familiar with pointers. My main question is Does const char* actually store a memory address? This question arose when working with strings. How can you assign a string to what is supposed to hold a memory address?

#include <iostream>

int main(void) {
    const char* x = "Hello";
    std::cout << x << std::endl; // Returns Hello
    std::cout << &x << std::endl; // Returns the actual address
}

To my knowledge the above code should print a memory address, so what actually is a char*?

2 Answers

char* does in fact store an address. When you assign a constant string, C++ puts that constant string somewhere convenient (probably in the .DATA section of the executable) and stores a pointer to it in the variable x. In particular, this is one of the reasons a constant character string is, well, const. The string of text that the const char* points to may be used in other places in the code.

Note that cout has special behavior when printing character arrays. When you do &x, you're actually getting the address of the local variable, i.e. a thing of type const char**. If you want the actual address of the string, you can use (void*)x to suppress the usual string printing behavior.

const char* indeed holds a memory address, not the string. In order for this to work, the compiler needs to perform some "magic": it places the content of the string literal at some address in the memory, and then sets that address into your const char* pointer. Therefore, the pointer stores the memory address of the initial character of your string.

One of the consequences of this is that you cannot get the length of your string directly from the const char* pointer: you need to go through a function to get the length.

Related