✏️ Explanatory Question

When can void pointer and null pointer be used in C?

👁 969 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Void pointer is a generic pointer that can be used to point another variable of any data type. Null pointer is a pointer which is pointing to nothing.

When Can Void Pointer and Null Pointer Be Used in C?

In C programming, void pointers and null pointers serve different purposes. A void pointer is used when the data type of the object being pointed to is unknown or can vary, while a null pointer is used to indicate that a pointer is not pointing to any valid memory location.

1. Void Pointer

A void pointer (also called a generic pointer) can store the address of any data type. It is declared using the void * syntax.

Syntax

void *ptr;

When is a Void Pointer Used?

  • When a function needs to work with different data types.
  • In generic programming.
  • In memory allocation functions such as malloc().
  • When the data type of the object is not known in advance.

Example of a Void Pointer

#include 

int main() {
    int num = 10;
    void *ptr = #

    printf("%d", *(int *)ptr);

    return 0;
}

Since a void pointer does not know the type of data it points to, it must be typecast before dereferencing.

2. Null Pointer

A null pointer is a pointer that does not point to any valid memory location. It is assigned the value NULL.

Syntax

int *ptr = NULL;

When is a Null Pointer Used?

  • To initialize a pointer before assigning it a valid address.
  • To indicate that a pointer is currently not in use.
  • To check whether memory allocation was successful.
  • To avoid dangling pointers after freeing memory.

Example of a Null Pointer

#include 

int main() {
    int *ptr = NULL;

    if (ptr == NULL) {
        printf("Pointer is not pointing to any memory location.");
    }

    return 0;
}

Difference Between Void Pointer and Null Pointer

Void Pointer Null Pointer
Can point to any data type. Points to no valid memory location.
Declared using void *. Assigned using NULL.
Requires typecasting before dereferencing. Cannot be dereferenced safely.
Used for generic programming. Used to represent an empty or invalid pointer.

Key Point

A void pointer is used when a pointer needs to handle different types of data, while a null pointer is used to indicate that a pointer currently does not reference any valid memory location. Both are important concepts for safe and efficient memory management in C programming.