What is void pointer in C?

C Programming Language >   Pointer in C Language >   Void/Generic Pointers  

Short Question

1019


Answer:

  • Void pointer is a generic pointer that can be used to point another variable of any data type.
  • Void pointer can store the address of variable belonging to any of the data type. So, void pointer is also called as general purpose pointer.

Note:
int pointer can be used to point a variable of int data type and char pointer can be used to point a variable of char data type.


In C, a void pointer, also known as a generic pointer, is a special pointer type that can hold the address of an object of any data type. It is declared using the void * type.

The void * type is considered "generic" because it lacks a specific data type. It allows a pointer to be assigned and manipulated without specifying the data type of the object it points to. However, you cannot directly dereference a void pointer or perform pointer arithmetic on it, as the compiler does not know the size or type of the object being pointed to.

Here's an example illustrating the use of a void pointer:


#include <stdio.h>

int main() {
    int num = 42;
    float pi = 3.14159;
    char letter = 'A';

    void* ptr;

    ptr = &num;
    printf("Value pointed by ptr: %d\n", *(int*)ptr);

    ptr = &pi;
    printf("Value pointed by ptr: %.5f\n", *(float*)ptr);

    ptr = &letter;
    printf("Value pointed by ptr: %c\n", *(char*)ptr);

    return 0;
}

In the above example, a void pointer ptr is declared. It is then assigned the address of different variables (num, pi, and letter) successively. By explicitly casting ptr to the appropriate type (int*, float*, or char*) before dereferencing it, we can access the values pointed to by the void pointer.

Note that when using void pointers, you need to ensure proper type casting and handle them with caution, as there is no type checking at compile-time. It is crucial to cast the void pointer to the correct type before dereferencing it to avoid errors and maintain type safety.


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.