0

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?

Jim Simson
  • 2,774
  • 3
  • 22
  • 30
Hormesis
  • 11
  • 4
  • 1
    Did you mean to write: `const char* myPointer2 = myPointer1;`? And what's `myPointer3 ` You seem to have some missing parts in your demo code. – πάντα ῥεῖ Sep 12 '20 at 08:01
  • ... or maybe typos. Please clarify. – Yunnosch Sep 12 '20 at 08:03
  • @πάνταῥεῖ you are right , sorry i meant const char* myPointer2 = myPointer1; – Hormesis Sep 12 '20 at 08:09
  • `myPointer1` and `myPointer2` are different variables, so they have different addresses - try `cout << (&myPointer1 == &myPointer2);` to verify. They both have the same value - try `cout << (myPointer1 == myPointer2);` to verify. – dxiv Sep 12 '20 at 08:09

1 Answers1

2

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;
}
super
  • 12,335
  • 2
  • 19
  • 29
  • what you wrote prints the content of the variable (here "Hallo") not the adress of the pointer – Hormesis Sep 12 '20 at 08:05
  • @Hormesis Yes. `std::cout` has an overload that takes a `char*` and prints it as a string. Printing both the pointers would both print "Hallo", showing that they point to the same thing. – super Sep 12 '20 at 08:10
  • @Hormesis `the content of the variable (here "Hallo")` No, the content of `myPointer` is *not* "Hallo". It is the address of an anonymous `const char[]` array which contains `"Hallo"`. – dxiv Sep 12 '20 at 08:12
  • @Hormesis It's since `myPointer1` and `myPointer2` are also separate variables, with their own addresses. You can have a `const char**`, a pointer to a pointer to char. `const char** myPointerToPointer = &myPointer1;` for example. The pointer has a value, the address it pointes to. But it's also a variable with it's own address. – super Sep 12 '20 at 08:27