The Wayback Machine - https://web.archive.org/web/20241105183421/https://www.geeksforgeeks.org/null-pointer-in-c/
Open In App

NULL Pointer in C

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Null Pointer is the pointer that does not point to any location but NULL. According to C11 standard:

“An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.”

Syntax of Null Pointer Declaration in C

type pointer_name = NULL;
type pointer_name = 0;

We just have to assign the NULL value. Strictly speaking, NULL expands to an implementation-defined null pointer constant which is defined in many header files such as “stdio.h”, “stddef.h”, “stdlib.h” etc. If you’re interested in learning how to handle pointers safely and efficiently in data structures, the C Programming Course Online with Data Structures provides expert guidance on this topic

Uses of NULL Pointer in C

Following are some most common uses of the NULL pointer in C:

  1. To initialize a pointer variable when that pointer variable hasn’t been assigned any valid memory address yet.
  2. To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer-related code, e.g., dereference a pointer variable only if it’s not NULL.
  3. To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
  4. A NULL pointer is used in data structures like trees, linked lists, etc. to indicate the end.

Check if the pointer is NULL

It is a valid operation in pointer arithmetic to check whether the pointer is NULL. We just have to use isequal to operator ( == ) as shown below:

ptr == NULL;

The above equation will be true if the pointer is NULL, otherwise, it will be false.

Examples of NULL Pointer in C

Example 1: C Program to avoid segmentation fault while accessing the value of pointer using NULL pointer

C
// C NULL pointer demonstration
#include <stdio.h>

int main()
{
    // declaring null pointer
    int* ptr = NULL;

    // derefencing only if the pointer have any value
    if (ptr == NULL) {
        printf("Pointer does not point to anything");
    }
    else {
        printf("Value pointed by pointer: %d", *ptr);
    }
    return 0;
}

Output
Pointer does not point to anything

By specifically mentioning the NULL pointer, the C standard gives a mechanism using which a C programmer can check whether a given pointer is legitimate or not.

Example 2: C Program to check successful memory allocation using malloc()

The malloc() function returns the NULL pointer when the memory allocation is failed. We will use this property to check if the memory allocation is successful.

C
// C Program to use NULL pointer to check for melloc error
#include <stdio.h>
#include <stdlib.h>

int main()
{

    // declaring dynamic memory for ptr
    int* ptr = (int*)malloc(5 * sizeof(int));

    // checking if the memory allocation is successful
    if (!ptr) {
        printf("Memory Allocation Failed");
        exit(0);
    }

    return 0;
}

Example 3: Dereferencing a NULL Pointer in C

What’s going to happen if we use the following C code:

C
// Trying to dereferencing a null pointer
#include<stdio.h>
int main()
{
int * ptr = NULL;
printf("%d",*ptr);
return 0;
}

On some machines, the above would compile successfully but crash when the program is run. Though that doesn’t mean it would show the same behavior across all the machines. As the value of NULL in predefined libraries is 0 and the pointer (that’s pointing to NULL) is not pointing to any memory location, this behavior occurs.

Example 4: C Program to demonstrate how to pass NULL to a function

We can pass a NULL value for pointers that should not contain any value to the function in C.

C
// C Program to illustrate how passing NULL works
#include <stdio.h>

void foo(int* string)
{
    if (string == NULL) {
        printf("NULL Pointer Passed");
        return;
    }
    printf("Non-Null Pointer Passed");
}

int main()
{

    foo(NULL);
    return 0;
}

Output
NULL Pointer Passed

Difference Between NULL Pointer and Void Pointer in C

The following table list the differences between a null pointer and a void pointer in C:

NULL Pointer

Void Pointer

A NULL pointer does not point to anything. It is a special reserved value for pointers.A void pointer points to the memory location that may contain typeless data.
Any pointer type can be assigned NULL.It can only be of type void.
All the NULL pointers are equal.Void pointers can be different.
NULL Pointer is a value.A void pointer is a type.
Example: int *ptr = NULL;Example: void *ptr;


Previous Article
Next Article

Similar Reads

C - Pointer to Pointer (Double Pointer)
Prerequisite: Pointers in C The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to cha
5 min read
Difference between Dangling pointer and Void pointer
Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. There are three different ways where Pointer acts as a dangling pointer: By deallocating memoryFunction CallWhen the variable goes out of scope Void pointer: Void pointer is a specific pointer type – void * – a pointer that point
2 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction Consider the following program: [GFGTABS] C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer th
9 min read
Passing NULL to printf in C
Consider the following C code snippet. char* p = NULL; printf("%s", p); What should be the output of the above program? The print expects a '\0' terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior. According to Section 7.1.4(of C99 or C11) : Use of library functions If
1 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deallocated memory), Void (pointing to some data locati
6 min read
How to declare a pointer to a function?
While a pointer to a variable or an object is used to access them indirectly, a pointer to a function is used to invoke a function indirectly. Well, we assume that you know what it means by a pointer in C. So how do we create a pointer to an integer in C? Huh..it is pretty simple... int *ptrInteger; /*We have put a * operator between int and ptrInt
2 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the & operator array is an alias for &array[0
1 min read
C | Pointer Basics | Question 1
What is the output of following program? # include <stdio.h> void fun(int x) { x = 30; } int main() { int y = 20; fun(y); printf("%d", y); return 0; } (A) 30 (B) 20 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using
1 min read
C | Pointer Basics | Question 2
Output of following program? # include <stdio.h> void fun(int *ptr) { *ptr = 30; } int main() { int y = 20; fun(&y); printf("%d", y); return 0; } (A) 20 (B) 30 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value
1 min read
C | Pointer Basics | Question 3
Output of following program? #include <stdio.h> int main() { int *ptr; int x; ptr = &x; *ptr = 0; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); *ptr += 5; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); (*ptr)++; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr);
2 min read
C | Pointer Basics | Question 4
Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes. #include <stdio.h> int main() { int arri[] = {1, 2 ,3}; int *ptri = arri; char arrc[] = {1, 2 ,3}; char *ptrc = arrc; printf("sizeof arri[] = %d ", sizeof(arri)); printf("sizeof ptri = %d ", sizeof(ptri)); printf("sizeof arrc[] =
1 min read
C | Pointer Basics | Question 17
Assume that float takes 4 bytes, predict the output of following program. #include <stdio.h> int main() { float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &arr[0]; float *ptr2 = ptr1 + 3; printf("%f ", *ptr2); printf("%d", ptr2 - ptr1); return 0; } (A) 90.500000 3 (B) 90.500000 12 (C) 10.000000 12 (D) 0.5000
1 min read
C | Pointer Basics | Question 6
#include<stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; } Assume that an int variable takes 4 bytes and a
2 min read
C | Pointer Basics | Question 7
#include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } What is the output of above program? (A) Machine dependent (B) 513 (C) 258 (D) Compiler Error Answer: (A) Explanation: Output is 513 in a little endian machine. To understand this output, let integers be sto
1 min read
C | Pointer Basics | Question 8
C/C++ Code int main() { char *ptr = \"GeeksQuiz\"; printf(\"%c", *&*&*ptr); return 0; } (A) Compiler Error (B) Garbage Value (C) Runtime Error (D) G Answer: (D)Explanation: The operator * is used for dereferencing and the operator & is used to get the address. These operators cancel out effect of each other when used one after another. We can a
1 min read
C | Advanced Pointer | Question 1
C/C++ Code void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf(\"%d\", *p); return 0; } (A) 10 (B) 20 (C) Compiler error (D) Runtime Error Answer: (B)Explanation: Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains uneffected. If we want to change a local poi
2 min read
C | Advanced Pointer | Question 2
Assume sizeof an integer and a pointer is 4 byte. Output? #include <stdio.h> #define R 10 #define C 20 int main() { int (*p)[R][C]; printf("%d", sizeof(*p)); getchar(); return 0; } (A) 200 (B) 4 (C) 800 (D) 80 Answer: (C) Explanation: Output is 10*20*sizeof(int) which is “800â€ģ for compilers with integer size as 4 bytes. When a point
1 min read
C | Pointer Basics | Question 17
#include<stdio.h> void fun(int arr[]) { int i; int arr_size = sizeof(arr)/sizeof(arr[0]); for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); } int main() { int i; int arr[4] = {10, 20 ,30, 40}; fun(arr); return 0; } (A) 10 20 30 40 (B) Machine Dependent (C) 10 20 (D) Northing Answer: (B) Explanation: In C, array parameters are
2 min read
C | Pointer Basics | Question 10
The reason for using pointers in a C program is (A) Pointers allow different functions to share and modify their local variables. (B) To pass large structures so that complete copy of the structure can be avoided. (C) Pointers enable complex “linked\" data structures like linked lists and binary trees. (D) All of the above Answer: (D)Explanation: S
1 min read
C | Pointer Basics | Question 11
C/C++ Code #include void f(int *p, int *q) { p = q; *p = 2; } int i = 0, j = 1; int main() { f(&i;, &j;); printf(\"%d %d", i, j); getchar(); return 0; } (A) 2 2 (B) 2 1 (C) 0 1 (D) 0 2 Answer: (D)Explanation: See below f() with comments for explanation. /* p points to i and q points to j */ void f(int *p, int *q) { p = q; /* p also points to j now */
1 min read
C | Pointer Basics | Question 12
Consider this C code to swap two integers and these five statements after it: void swap(int *px, int *py) { *px = *px - *py; *py = *px + *py; *px = *py - *px; } S1: will generate a compilation error S2: may generate a segmentation fault at runtime depending on the arguments passed S3: correctly implements the swap procedure for all input pointers r
1 min read
C | Pointer Basics | Question 13
int f(int x, int *py, int **ppz) { int y, z; **ppz += 1; z = **ppz; *py += 2; y = *py; x += 3; return x + y + z; } void main() { int c, *b, **a; c = 4; b = &c; a = &b; printf("%d ", f(c, b, a)); return 0; } (A) 18 (B) 19 (C) 21 (D) 22 Answer: (B) Explanation: Let us understand this line by line /* below line changes value of c to
1 min read
C | Pointer Basics | Question 14
Predict the output of following program #include<stdio.h> int main() { int a = 12; void *ptr = (int *)&a; printf("%d", *ptr); getchar(); return 0; } (A) 12 (B) Compiler Error (C) Runt Time Error (D) 0 Answer: (B) Explanation: There is compiler error in line "printf("%d", *ptr);". void * type pointers cannot be de-referenced. We
1 min read
C | Advanced Pointer | Question 3
#include <stdio.h> int main() { int a[5] = {1,2,3,4,5}; int *ptr = (int*)(&a+1); printf("%d %d", *(a+1), *(ptr-1)); return 0; } (A) 2 5 (B) Garbage Value (C) Compiler Error (D) Segmentation Fault Answer: (A) Explanation: The program prints “2 5â€ģ. Since compilers convert array operations in pointers before accessing the array ele
1 min read
C | Advanced Pointer | Question 4
#include <stdio.h> char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"}; char **cp[] = {c+3, c+2, c+1, c}; char ***cpp = cp; int main() { printf("%s ", **++cpp); printf("%s ", *--*++cpp+3); printf("%s ", *cpp[-2]+3); printf("%s ", cpp[-1][-1]+1); return 0; } (A) TEST s
1 min read
C | Pointer Basics | Question 15
#include<stdio.h> void swap (char *x, char *y) { char *t = x; x = y; y = t; } int main() { char *x = "geeksquiz"; char *y = "geeksforgeeks"; char *t; swap(x, y); printf("(%s, %s)", x, y); t = x; x = y; y = t; printf("\n(%s, %s)", x, y); return 0; } (A) (geeksquiz, geeksforgeeks) (geeksforgeeks, geeksqui
1 min read
C | Pointer Basics | Question 16
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int *p = arr; ++*p; p += 2; printf("%d", *p); return 0; } (A) 2 (B) 3 (C) 4 (D) Compiler Error Answer: (B) Explanation: The expression ++*p is evaluated as "++(*p)" . So it increments the value of first element of array (doesn't change the pointer p). When p += 2 is done,
1 min read
C | Advanced Pointer | Question 5
Predict the output #include <string.h> #include <stdio.h> #include <stdlib.h> void fun(char** str_ref) { str_ref++; } int main() { char *str = (void *)malloc(100*sizeof(char)); strcpy(str, "GeeksQuiz"); fun(&str); puts(str); free(str); return 0; } (A) GeeksQuiz (B) eeksQuiz (C) Garbage Value (D) Compiler Error Answer
1 min read
C | Advanced Pointer | Question 7
Assume that the size of int is 4. #include <stdio.h> void f(char**); int main() { char *argv[] = { "ab", "cd", "ef", "gh", "ij", "kl" }; f(argv); return 0; } void f(char **p) { char *t; t = (p += sizeof(int))[-1]; printf("%s\n", t); } (A) ab (B) cd (C) ef (D) gh Answer: (D)
1 min read
C | Advanced Pointer | Question 8
C/C++ Code (A) 2 3 5 6 (B) 2 3 4 5 (C) 4 5 0 0 (D) none of the above Answer: (A) Explanation: In the above code, we have declared: int a[][3] = {1, 2, 3, 4, 5, 6}; This line declares a 2D array with 2 rows and 3 columns. The elements are initialized in row-major order: 1, 2, and 3 are the elements of the first row, and 4, 5, and 6 are the elements
2 min read
Article Tags :
three90RightbarBannerImg