Null Pointer In C
Null Pointers Definition :
A pointer that doesn’t point to any memory location is called a Null Pointer in C.It saves the segment’s base address.While void is the pointer’s type, the null pointer essentially holds the Null value.
Syntax :
int * ptr = NULL;
Null Pointers :
A pointer is referred to as a null pointer if there is no address that can be allocated to it. The pointer is regarded as a Null pointer when a NULL value is assigned to it.
Example :
Run
#include<stdio.h> void main () { int val1, val2; int *ptr = 0; if (ptr == 0) { ptr = &val1; val1 = 5; } if (ptr == 0) { ptr = &val2; val2 = 10; } printf ("value of *ptr: %d ", *ptr); }
Output :
value of *ptr: 5
Uses of Null Pointers :
- used to initialise a pointer variable when no proper memory address has yet been assigned to it.
- used to pass a null pointer as a function argument when no valid memory address should be passed.
- prior to accessing any pointer variable, used to check for a null pointer.
In order to handle errors in pointer-related code, for example, dereference pointer variables only if they are not NULL.
Application of Null Pointers in C :
- When the pointer variable is not given a memory address
- While using malloc() function, we use Null Pointers.
- You should validate a pointer before dereferencing it. It stops unpredictable behaviour .It helps in handling errors as well.
Example :
Run
#include<stdio.h> int main() { int * ptr =NULL; // declaration of null pointer if(ptr!=NULL) { printf("Value of ptr is : %d",* ptr); } else { printf("Pointer is invalid"); } return 0; }
Output :
Pointer is invalid
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others