Shouvik Shouvik - 1 year ago 95
C++ Question

What is a void pointer and what is a null pointer?

So I was going through some interview questions an I came across this question

The answer to the question confused me throughly! It seems void and null could be used interchangeably according to this question and I don't believe that to be correct. I assumed void to be a return type and null to be a value. But I am just a code-rookie and am not sure I know right. Hence to all the gurus out there.. If you could shed some light it would be extremely beneficial! :)

Please express your views as to what a null pointer is and a void pointer is. Not looking for difference between null and void. Also please verify the answer of the question and tell me if that is correct... Thanks

Answer Source

The two concepts are orthogonal:

  1. A void pointer, (void *) is a raw pointer to some memory location.
  2. A null pointer is a special pointer that doesn't point to anything, by definition. It can be a pointer to any type, void or otherwise.

A void pointer can be null or not:

void *void_ptr1 = NULL;
void *void_ptr2 = malloc(42);
void *void_ptr3 = new Foo;               // void * can point to almost anything
void *void_ptr4 = (char*)void_ptr3 + 1;  // even somewhere inside an object

A non-void pointer can also be null or not:

Foo *f = NULL;
Foo *g = new Foo;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download