0
0
Power-electronicsConceptBeginner · 3 min read

What is Void Pointer in Embedded C: Explanation and Example

A void pointer in Embedded C is a special pointer that can hold the address of any data type without specifying its type. It is used when you want a generic pointer that can point to different types of data during program execution.
⚙️

How It Works

Think of a void pointer as a universal remote control that can connect to any device, but it doesn't know what buttons to press until you tell it. In Embedded C, a void pointer holds the memory address of any variable, but it does not know the type or size of the data stored there.

This means you cannot directly use a void pointer to read or write data. You must first tell it what type of data it points to by converting (casting) it to a specific pointer type. This flexibility helps when writing functions or code that work with different data types without repeating code.

💻

Example

This example shows how a void pointer can point to an integer and a float by casting it appropriately before use.

c
#include <stdio.h>

int main() {
    int a = 10;
    float b = 5.5f;
    void *ptr;  // void pointer

    ptr = &a;  // point to int
    printf("Value of a = %d\n", *(int *)ptr);  // cast to int pointer

    ptr = &b;  // point to float
    printf("Value of b = %.2f\n", *(float *)ptr);  // cast to float pointer

    return 0;
}
Output
Value of a = 10 Value of b = 5.50
🎯

When to Use

Use void pointers in Embedded C when you need a generic pointer that can handle multiple data types. This is common in functions that work with different kinds of data, like memory management routines or hardware drivers where data types vary.

For example, a function that copies memory blocks can accept a void pointer so it can copy any type of data without knowing its exact type. This makes your code more flexible and reusable.

Key Points

  • A void pointer can hold the address of any data type.
  • You must cast a void pointer to the correct type before dereferencing it.
  • Void pointers are useful for writing generic and reusable code.
  • They cannot be directly dereferenced without casting.

Key Takeaways

A void pointer is a generic pointer that can point to any data type in Embedded C.
Always cast a void pointer to the correct type before accessing the data it points to.
Void pointers enable writing flexible and reusable code for different data types.
They are commonly used in memory handling and hardware interfacing functions.