Reputation: 51
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.
Upvotes: 1
Views: 55
Reputation: 409136
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;
Upvotes: 7