1

I have created some pointer in code but the results are not what I expected.

Here is the simple code:

int main(int argc, char const* argv[])
{
    int myInt = 23;
    int* ptr = &myInt;

    char* buffer = new char[8];
    memset(buffer, 0, 8);

    char** ptr2 = &buffer;

    std::cout << "ptr address is " << ptr << std::endl;
    std::cout << "buffer pointer is pointing to address " << buffer << std::endl;
    std::cout << "ptr2 pointer is pointing to address " << ptr2 << std::endl;
    std::cout << "Dereferencing ptr2 = " << *ptr2 << std::endl;
    return 0;
} 

And here are the results of running the code:

ptr address is 0x7ffde215a14c

buffer pointer is pointing to address

ptr2 pointer is pointing to address 0x7ffde215a150

Dereferencing ptr2 =

I am wondering why the buffer pointer address does not show and why the dereferencing of ptr2 also shows nothing and yet the pointer (ptr2) pointing to the buffer pointer is showing that address. None of this makes any sense to me.

walnut
  • 21,629
  • 4
  • 23
  • 59
Clan
  • 51
  • 4
  • `*ptr2` is interpreted as a nul-terminated C style string. – Eljay Oct 19 '19 at 14:29
  • Possible duplicate of [cout << with char\* argument prints string, not pointer value](https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value) – eesiraed Oct 19 '19 at 17:15

1 Answers1

7

The stream << operator is explicitly overloaded for all kinds of char* to print it as a null-terminated string. To print the pointer you need to cast it:

std::cout << "buffer pointer is pointing to address " << reinterpret_cast<void*>(buffer) << std::endl;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Why `reinterpret_cast`, isn't `static_cast` safer in that it preserves the pointer value? – Empty Space Oct 19 '19 at 15:13
  • OK, then why did it not print the string? – Clan Oct 19 '19 at 15:27
  • @Clan The string is interpreted as a *null-terminated* string, and remember that your string is filled with null characters. Think about what that means. – eesiraed Oct 19 '19 at 17:13
  • @AlexanderZhang I believe we can do it in certain cases. See 10th point in explanation section of https://en.cppreference.com/w/cpp/language/static_cast. – Empty Space Oct 19 '19 at 17:15
  • 1
    This answer https://stackoverflow.com/a/573345/12160191 says `For casting to and from void*, static_cast should be preferred`. – Empty Space Oct 19 '19 at 17:18
  • @TrickorTreat Sorry I forgot you can do so for `void*`. – eesiraed Oct 19 '19 at 17:18