c++pointerschar-pointer

Pointer address and address of variables to which pointer points


I am a newbie in c++ and my question may seem basic, but your answer could help me and help others.

I created to char pointer myPointer1 und myPointer2 so

const char *myPointer1 = "Hallo";
const char* myPointer2 = myPointer;

I thought that pointer stored the address of the variables they point to. In this case we have just one variable "Hallo" and both pointers should then points to the same address. but when i print :

cout << &myPointer1 << endl << endl;
cout << &myPointer2 << endl << endl;

the results are two different adresses:

009EFC00
009EFBE8

Could anyone help?


Solution

  • You are printing the address of the pointer, not the address that the pointer points to.

    std::cout << myPointer << std::endl;
    

    This would print the address the pointer points to.

    Since a char* is treated as a string when passed to std::cout it will print Hallo.

    If you want to print the address itself you can achieve that by casting it to a const void* and printing that.

    #include <iostream>
    
    int main() {
      const char *myPointer1 = "Hallo";
      const char* myPointer2 = myPointer1;
    
      std::cout << static_cast<const void*>(myPointer1) << std::endl;
      std::cout << static_cast<const void*>(myPointer2) << std::endl;
    }