What is NULL Pointer?
A NULL pointer is a pointer that does not point to any memory location. It represents an invalid memory location.
When a NULL value is assigned to a pointer, then the pointer is considered as NULL pointer.
Example:
int main(){
int *ptr = NULL;
return 0;
}
Used of NULL Pointer
- It is used to initialize a pointer when that pointer isn’t assinged any valid memory address yet.
Example:
int main(){
int *ptr = NULL;
return 0;
}
- Useful for handling errors when using malloc function.
Example:
#include
#include
int main(){
int *ptr;
ptr = (int*)malloc(2*sizeof(int));
if(ptr==NULL){
printf("Memory could not be allocated");
}else{
printf("Memory allocated successfully.");
}
return 0;
}
Output:
Memory allocated successfully.
Facts About NULL Pointer
- The value of NULL is 0. we can either use NULL or 0 but this 0 is written in context of pointers and is not equivalent to the integer.
Example:
int main(){
int *ptr = NULL;
printf("%d", ptr);
return 0;
}
Output:
0
- Size of the NULL pointer depends upon the platform and is similar to the size of the normal pointers.
Example:
int main(){
printf("%d",sizeof(NULL));
return 0;
}
Output:
8
