Void Pointer in C

Void Pointer in C

In this article, I am going to discuss Void Pointer in C with Examples. Please read our previous articles, where we discussed the Null Pointer in C.

Void Pointer in C:

The Generic pointer of C & C++ is called a void pointer. Generic pointer means it can access and manipulate the data of any kind of variable. The Size of the void pointer is 2 bytes. By using a void pointer, when we are accessing the data then it is mandatory to use Type casting mechanism else it will give you an error. When we are working with the void pointer, type specification will be decided at run time only. When we are working with the void pointer, arithmetic operations are not allowed, i.e. incrementation and decrementation of the pointer are restricted.

Program:
#include<stdio.h>
void main ()
{
    int i;
    float f;
    char ch;
    int *iptr = (int *) 0;
    float *fptr = (float *) 0;
    char *cptr = (char *) 0;
    iptr = &i;
    i = 10;
    printf ("\n %d %d ", i, *iptr);
    fptr = &f;
    f = 12.8;
    printf ("\n %d %d", f, *fptr);
    cptr = &ch;
    ch = 'A';
    printf ("\n %d %d", ch, *cptr);
}

Output:

Void Pointer in C

In the previous program, in place of constructing 3 types of pointers, we can create a single pointer variable that can access & manipulate any kind of variable properly, i.e. void pointer.

Program:
#include<stdio.h>
void main ()
{
    int i;
    float f;
    char ch;
    void *ptr;
    ptr = &i;
    *(int *) ptr = 10;
    printf ("\n %d %d", i, *(int *) ptr);
    ptr = &f;
    *(float *) ptr = 12.8;
    printf ("\n %f %f", f, *(float *) ptr);
    ptr = &ch;
    *(char *) ptr = 'A';
    printf ("\n %c %c", ch, *(char *) ptr);
}

Output:

Void Pointer Examples in C Language

Program:
#include<stdio.h>
void main ()
{
    int a, b;
    char *ptr;
    ptr = &a;
    a = -1;
    b = *(int *) ptr;
    printf ("\n %d %d %d", a, b, *(unsigned *) ptr);
    *(int *) ptr = 32767;
    printf ("\n %d %d %d", a, b, *(unsigned char *) ptr);
}

Output:

Void Pointer in C Language with Examples

In the next article, I am going to discuss Dangling Pointer in C language. Here, in this article, I try to explain Void Pointer in C. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *