NULL Pointer:
If in case the pointer variable does not point to any memory location, then it’s good practice to assign a NULL value to the pointer variable. The pointer variable with a NULL value is called the NULL pointer.
A null pointer is a constant pointer with value 0(zero) defined in studio.h header. Memory at address 0 is reserved by the operating system and we cannot access this location. Accessing this location gives us undefined behavior.
Using the null pointer, we can avoid the misuse of unused pointers and prevent pointer variables from having some garbage values assigned to them.
Void Pointers:
Void pointers are special pointers that point to values with no type. The void pointers are more flexible as they can point to any type. But they cannot be directly dereferenced. For dereferencing, the void pointer needs to be converted to a pointer that points to a value with the concrete data type.
Sample Code:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
void *vptr;
int val = 10;
printf ("\Null pointer value is: %d\n", ptr);
ptr = &val;
printf ("\n Value is: %d\n", *ptr);
vptr = (int*) ptr; ==>Typecasting to proper type
printf ("\n Void pointer points to: %d\n", *vptr);
return 0;
}
Output:
Null pointer value is: 0
Value is: 10
Void pointer points to: 10
Categories: C Language
Leave a Reply