So I was going through some interview questions and I came across one about void and null pointers, which claims:
a pointer with no return type is called a null pointer. It may be any kind of datatype.
This confused me thoroughly! 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 am right.
Please express your views as to what a null pointer is and a void pointer is. I am not looking for difference between null and void.
The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
The difference between null and void as term for nothing stems from their place in physical space. A void is nothing but takes up space; null is nothing at all. In other words, you could measure a void but null offers nothing to measure. 4.1 Void is used to indicate that a function/method does not return any data type.
A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.
The two concepts are orthogonal:
void *
) is a raw pointer to some memory location.A void pointer can be null or not:
void *void_ptr1 = nullptr;
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 = nullptr;
Foo *g = new Foo;
Just plain forget about that answer. A quote from your link :
"a pointer with no return type is called a null pointer."
This is sooo plain WRONG. A pointer's return type? REALLY? This is a bad source...
void*
is universal pointer type because any pointer type (except for pointer to const and/or volatile) can be implicitly converted to void*
. In other words, you can assign any pointer to a variable of type void*
. A null pointer is a pointer value 0
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