What is void Pointer in C Explained- Free Online C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

void Pointer in C Explained

Chapter 8 · Pointers · The generic pointer that can hold any object address, and the casting rules that keep it safe

Topics covered in this free C tutorial

void pointer in C free C programming course free C tutorial generic pointer C programming for embedded systems free embedded C course

In this lecture of our free C programming course we meet the void pointer in C, also called the generic pointer. Every other pointer type you have used so far is strict: an int * may only hold the address of an int. A void * breaks that rule on purpose. It can hold the address of an int, a float, a structure or a buffer, and that flexibility is why it appears in malloc, memcpy, qsort, RTOS task parameters and nearly every callback interface. This free C tutorial shows how it works, why you cannot dereference it directly, and how to use it safely in embedded C programming.

What You Will Learn

  • What a void pointer in C is and how to declare one
  • Which pointer assignments are legal and which the compiler rejects
  • Why dereferencing a void * directly is an error
  • How to cast before you dereference, and how to read the cast expression
  • How to write one function that works on several data types
  • The common mistakes, and the rules that keep generic code safe

Prerequisites

Before you start

You need to understand pointer declaration, the address-of operator, dereferencing, and the fact that a pointer’s type tells the compiler how many bytes to read and how to interpret them. A quick refresher on sizeof and on enum will also help with the examples.

What Is a void Pointer in C?

The word void normally means “no value”, as in a function that returns nothing. In a pointer declaration it means “no type information about the object being pointed at”:

void *vpt;

Here vpt is a pointer variable. It stores an address, like any other pointer, but the compiler knows nothing about what lives there: not its size, not whether it is an integer or a float. That is why a void pointer in C is called generic. It is a general-purpose address holder, and the programmer carries the type knowledge.

One void pointer, many possible targets

void *vp
can hold the address of
int gain
void *vp
or the address of
float volts
void *vp
or the address of
double ratio

Assignment rules at a glance

StatementLegal in C?Reason
ip = fp; (int * from float *)No, compiler diagnostictwo different object pointer types
vp = ip;Yesany object pointer converts to void *
vp = fp;Yessame rule, any object type
ip = vp;Yes, no cast needed in Cvoid * converts back to any object pointer
vp = &constant_object;Diagnostic if the object is constuse const void * to keep the qualifier
vp = function_name;Not guaranteed by ISO Cvoid * is for data pointers, not function pointers

C versus C++. In C you may assign a void * to any object pointer without a cast. C++ does not allow that and demands an explicit cast. If you ever share code between the two languages, keep this difference in mind.

Why You Cannot Dereference a void Pointer in C

To read through a pointer the compiler must know how many bytes to fetch and how to interpret them. For int * that means four bytes (on most systems) treated as a signed integer. For void * the type has no size and no meaning, so the expression *vp has no value. Let us trigger both mistakes on purpose.

#include <stdio.h>

int main(void)
{
    int   gain  = 3;
    float volts = 3.4f;
    int  *ip    = &gain;
    float *fp   = &volts;
    void *vp    = &gain;

    ip = fp;                            /* mismatched pointer types */
    printf("%d\n", *ip);
    printf("%d\n", *vp);                /* dereferencing a void *   */
    return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o bad_void bad_void_deref.c

Compiler output (GCC 13):

progs/bad_void_deref.c: In function 'main':
progs/bad_void_deref.c:11:8: warning: assignment to 'int *' from incompatible pointer type 'float *' [-Wincompatible-pointer-types]
   11 |     ip = fp;                            /* mismatched pointer types */
      |        ^
progs/bad_void_deref.c:13:20: warning: dereferencing 'void *' pointer
   13 |     printf("%d\n", *vp);                /* dereferencing a void *   */
      |                    ^~~
progs/bad_void_deref.c:13:20: error: invalid use of void expression

Two different messages appear. The first line is a warning about ip = fp: the types differ, so the compiler complains even though both are pointers. Newer GCC releases treat that as a hard error. The second is a true error: invalid use of void expression. The build stops because *vp is meaningless without a type.

Cast First, Then Dereference

The fix is to tell the compiler what type lives at the address, using a cast. Suppose vp holds the address of an int. Then:

*(int *)vp

Read it from the inside out. (int *)vp converts the generic pointer into an int *. The leftmost * then dereferences that converted pointer and yields an int. A cast and the unary star have the same precedence and associate right to left, so the cast is applied before the dereference. You can use the expression on the left of an assignment as well: *(int *)vp = 12; stores 12 at that address.

Example 1: One void pointer, three data types

#include <stdio.h>

int main(void)
{
    int    gain  = 3;
    float  volts = 3.4f;
    double ratio = 0.125;
    void  *vp;

    vp = &gain;                         /* any object address fits */
    printf("gain  = %d\n", *(int *)vp);

    *(int *)vp = 12;                    /* write through the void * */
    printf("gain  = %d (after the write)\n", gain);

    vp = &volts;
    printf("volts = %.2f\n", *(float *)vp);

    vp = &ratio;
    printf("ratio = %.3f\n", *(double *)vp);

    vp = &gain;
    int *ip = vp;                       /* void * to int *: no cast needed in C */
    printf("ip points at %d\n", *ip);
    return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o void_basic ep_void_basic.c
./void_basic
gain  = 3
gain  = 12 (after the write)
volts = 3.40
ratio = 0.125
ip points at 12

The same variable vp served three different objects. Each time we cast to match the object it currently held. The last two lines show the return trip: int *ip = vp; compiles with no cast in C, and the value 12 confirms that the earlier write went through to gain.

The cast must match the real object. A void pointer in C does not make every access legal. If vp holds the address of a float, reading it as *(int *)vp breaks the strict aliasing rule and is undefined behavior. The only exception is reading the raw bytes through unsigned char * or char *. If you really need to reinterpret bits, copy them with memcpy into an object of the other type.

A Generic Function Using a void Pointer in C

The classic use of void pointers is simple: a function that must do the same job on different data types receives a void *. But a bare void pointer carries no type, so the caller must say what the address holds. A common, readable way is a small tag. In the next program, ep_show accepts any object and prints it according to a kind argument.

#include <stdio.h>

typedef enum { KIND_INT, KIND_FLOAT, KIND_CHAR } kind_t;

/* one function, three data types: the tag tells us how to read the bytes */
static void ep_show(const void *p, kind_t kind)
{
    switch (kind) {
    case KIND_INT:
        printf("int   : %d\n", *(const int *)p);
        break;
    case KIND_FLOAT:
        printf("float : %.2f\n", *(const float *)p);
        break;
    case KIND_CHAR:
        printf("char  : %c\n", *(const char *)p);
        break;
    }
}

int main(void)
{
    int   retries = 42;
    float celsius = 36.6f;
    char  grade   = 'K';

    ep_show(&retries, KIND_INT);
    ep_show(&celsius, KIND_FLOAT);
    ep_show(&grade,   KIND_CHAR);
    return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o void_show ep_void_show.c
./void_show
int   : 42
float : 36.60
char  : K

Note the parameter type const void *. The function only reads the object, so the qualifier promises that it will not modify it, and callers may safely pass the address of a constant. Inside the function each case casts to a type that matches the tag. If a caller passes KIND_FLOAT with the address of an int, the program has a bug the compiler cannot see, which is the price of genericity.

Where You Meet void * in Real Code

WhereSignature or patternWhy void *
Memory allocationvoid *malloc(size_t size);it does not know what you will store
Copying bytesvoid *memcpy(void *dest, const void *src, size_t n);works on any object, counted in bytes
Sortingvoid qsort(void *base, size_t n, size_t size, ...);sorts arrays of any element type
RTOS taskstask function taking void *pvParameters (FreeRTOS)lets you pass any argument to a new task
Threadsvoid *(*start_routine)(void *) in pthread_createone entry type for all thread arguments and results
Callbacksa void *context or user_data parameterthe library passes your own data back to you

In C programming for embedded systems the last two rows are the ones you will write yourself most often: a driver stores a function pointer plus a void * context, and later calls the function with that context so your code can find its own data.

Benefits and Risks of the Generic Pointer

BenefitRisk
One function serves many types, so less duplicated codethe compiler cannot check the type, so errors appear at run time
Required for APIs such as malloc and memcpya wrong cast silently reads the wrong bytes
Makes callbacks with user context possiblethe caller and the callee must agree on the real type
Converts to and from every object pointercan hide that a const object is being modified

Common void Pointer Mistakes

  • Dereferencing without a cast: *vp will not compile.
  • Casting to the wrong type: the program compiles and prints nonsense or has undefined behavior.
  • Losing the type: storing a void * and forgetting what it pointed at. Keep a tag, a size, or documentation next to it.
  • Dropping const: assigning the address of a const object to a plain void * invites accidental writes. Use const void *.
  • Storing a function address in a void pointer: ISO C does not guarantee it. Use a proper function pointer type.
  • Misaligned casts: casting a void * that points at a byte buffer to uint32_t * may produce a misaligned access, which can fault on some microcontrollers.

Best Practices and Security Notes

  • Use a typed pointer whenever the type is known. Reach for void * only for genuinely generic interfaces.
  • Prefer const void * for input parameters that the function must not change.
  • Pass a size or a type tag along with the address, and validate it before reading. A generic function that trusts an unchecked length is a classic buffer over-read.
  • Cast once, into a well-named local variable, instead of repeating long casts in every expression.
  • Compile with -Wall -Wextra -pedantic. These flags catch most of the pointer type problems shown above.

Summary and Key Takeaways

Key takeaways

  • A void pointer in C holds the address of any object but carries no type, size or meaning.
  • Any object pointer converts to void * and back again; in C neither direction needs a cast.
  • You cannot dereference or step a plain void * without first casting it to a real pointer type.
  • Read *(int *)vp as: convert, then dereference.
  • The cast must match the real object, or the behavior is undefined.
  • Use const void * for read-only inputs and pair each pointer with a tag or size.

Conclusion

The void pointer in C is the language’s universal adapter. It lets library functions and callback interfaces handle data they know nothing about, and in return it asks you to keep the type information yourself. Practice the rule “cast first, then dereference” until it is automatic, and keep every generic function honest by passing a type tag or a size. The next lecture continues in this free embedded C course with the question that naturally follows: what happens when you try to do pointer arithmetic on a void pointer?

Frequently Asked Questions

What is a void pointer in C?

It is a pointer declared as void * that can hold the address of an object of any type. It stores only the address; it has no information about the type or size of the object.

Why can’t I dereference a void pointer?

The compiler does not know how many bytes to read or how to interpret them. Cast the pointer to the correct type first, for example *(int *)vp.

Do I need to cast when assigning a void pointer to an int pointer?

Not in C. A void * converts implicitly to any object pointer type. C++ requires an explicit cast.

Can a void pointer hold a function address?

ISO C does not guarantee it. Use a function pointer type for functions. Some platforms allow it as an extension, but portable code should not rely on it.

What is the difference between void * and const void *?

const void * promises that the code will not modify the pointed-to object through that pointer. Use it for read-only parameters so callers can pass constants without a diagnostic.

Where are void pointers used in embedded systems?

In memory allocation, memcpy, RTOS task parameters, and callback interfaces that carry a user context pointer so a driver can hand your own data back to you.

Is a void pointer the same as a NULL pointer?

No. void * is a type; NULL is a value, a pointer that points to nothing. A void * variable may hold a valid address or NULL, just like any other pointer.

Next up: void pointer arithmetic

You can store any address in a void pointer and read it back with a cast. Next we look at what happens when you try to move a void pointer forward.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →