Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ setting char pointer to null [duplicate]

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?

like image 351
Bbvarghe Avatar asked Jan 13 '23 05:01

Bbvarghe


2 Answers

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

like image 116
Mark Garcia Avatar answered Jan 22 '23 03:01

Mark Garcia


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);

like image 27
Tomer Arazy Avatar answered Jan 22 '23 02:01

Tomer Arazy