In Visual studio 2012, I was messing around with pointers, and I realized that this program kept crashing:
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const char* pointer = nullptr;
cout << "This is the value of pointer " << pointer << "." << endl;
return 0;
}
My intent was the set a pointer
to nullptr
, and then print the address. Even though the program compiles, it crashes during runtime. Can someone explain what is going on?
Also, what's the difference between pointer
and *pointer
?
You are using a const char*
which, when used in std::cout
's operator <<
, is interpreted as a string.
Cast it to void*
to see the pointer's value (the address it contains):
cout << "This the value of pointer " << (void*)pointer << "." << endl;
Or if you want to be pedantic:
cout << "This the value of pointer " << static_cast<void*>(pointer) << "." << endl;
LIVE EXAMPLE
Although you can do cout << "Pointer is " << (void*)pointer << ".\n";
as already been suggested I feel that in this case the "C way" of doing it is prettier (no casting) and more readable: printf("Pointer is %p\n",pointer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With