Skip to main content

Command Palette

Search for a command to run...

Void pointers

Updated
2 min readView as Markdown
Void pointers

Consider creating a program that reads information from a file. The data in the file can be of various types: integers, floating-point numbers, or even strings. How do you handle such diverse data without knowing its type in advance? This is where void pointers come into play.

Void pointers allow you to create a flexible data processing pipeline. You can read data from the file, store it using void pointers, and later, when you know its type, typecast the void pointer to the appropriate data type and work with the data seamlessly.

The Role of Typecasting

void pointers can point to data of any type, but they lack type information. To work with the data they point to, you need to tell the compiler how to interpret it. Here typecasting becomes relevant.

To typecast a void pointer, you use the desired data type in parentheses followed by the pointer variable. Here’s the basic syntax:

(datatype*)void pointer;

Program:

#include<stdio.h>

int main()
{
    int a = 56;
    float b = 4.5;
    char c = 'k';

    void *ptr; // declaration of void pointer.

    // assigning the address of variable 'a'.
    ptr=&a;
    printf("value of 'a' is : %d",*((int*)ptr));

    // assigning the address of variable 'b'.
    ptr=&b;
    printf("\nvalue of 'b' is : %f",*((float*)ptr));

    // assigning the address of variable 'c'.
    ptr=&c;
    printf("\nvalue of 'c' is : %c",*((char*)ptr));
    return 0;
}

Output:

Void pointers are particularly useful in the following scenarios:

  1. Generic Data Structures: When designing data structures like linked lists, trees, or queues that can store elements of different types.

  2. Dynamic Memory Allocation: When allocating memory dynamically for unknown data types, void pointers can store the memory address until you determine the correct type.

  3. Interfacing with External Libraries: When interfacing with external libraries or APIs that return data of unspecified types, void pointers can hold the data until you figure out its type.

12 views

More from this blog

P

Programming Tutorials

89 posts