C VOID Pointer

After a brief overview of pointers, it is time to begin with void pointers and their functionalities, which are a highly significant sort of pointers. Since functions that return nothing are given the type void, we already know that a void function has no return type. Pointers that have the datatype of a void can now be typecast into any other data type as needed in the case of those pointers. And that helps since it eliminates the need for us to first choose a data type for the pointer. General-purpose pointer variables can also be used to refer to void pointers. Let’s look at a few instances that show how void pointers can be used.

    int var = 1;

    void *voidPointer = &var;

Since we have stored the address of an integer value in the void pointer, its data type is typecast here into int.

    char x = ‘a’;

    void *voidPointer = &x;

As we have saved the address of a character value in the void pointer in this example, the data type of the pointer is typecast to char. You must also be reminded of how we used to type cast void pointers provided by the calloc() and malloc() routines while doing dynamic memory allocation. The heap also returns a void pointer to the requested memory there. A void pointer is useful in this situation since we could type cast the object to any other data type.

Two important features of a VOID pointer are:

Pointers that are void cannot be dereferenced. An illustration of this is possible with the aid of an example.

int a = 10;
    void *voidPointer;
    voidPointer = &a;
    printf("%d", *voidPointer);

OUTPUT: Compiler Error!

The fact that we cannot dereference a void pointer, which would require us to typecast the pointer each time it is used, causes his programme to crash at compilation time. This is the right way to do things.

    int a = 8;
    void *voidPointer;
    voidPointer = &a;
    printf("%d", *(int *)voidPointer);

Output:8

Due to the use of the type and the pointer, the compiler won’t produce any errors and will output the result immediately.

Since void pointers don’t retain any addresses, they can’t be utilised with pointer arithmetic to increase or decrease their value.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in