🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →void Pointer Arithmetic in C
Chapter 8 · Pointers · Why you cannot add 1 to a generic pointer, and the two correct ways to step through memory
Topics covered in this free C tutorial
Welcome to another lecture of our free C programming course. Last time we learned that a void * holds any address but cannot be dereferenced. Today’s topic is void pointer arithmetic: what happens when you write vp + 1, why standard C refuses it, why GCC quietly allows it, and how to move through memory correctly instead. This free C tutorial also builds two small generic functions, a swap and an array visitor, that rely on exactly the technique you will use in embedded C programming for buffers, protocol parsers and container libraries.
What You Will Learn
- How pointer arithmetic scales by the size of the pointed-to type
- Why void pointer arithmetic has no defined step size in standard C
- What the GCC extension does and why you should not depend on it
- Two correct ways to advance a
void *: cast to the real type, or step in bytes - How to write generic
swapandforeachhelpers usingvoid * - The alignment and overflow traps in generic code
Prerequisites
Before you start
Finish the lecture on the void pointer in C first. You also need the earlier lectures on pointer arithmetic, the sizeof operator, and function pointers at the level of “a pointer that can call a function”.
How Ordinary Pointer Arithmetic Works
When you add an integer n to a typed pointer, the compiler does not add n bytes. It adds n * sizeof(*p) bytes. That scaling is what makes p + 1 land on the next element of an array.
| Pointer type | Size of the pointed-to type | Bytes added by p + 1 |
|---|---|---|
char * | 1 | 1 |
short * | 2 | 2 |
int * | 4 (typical) | 4 |
float * | 4 (typical) | 4 |
double * | 8 (typical) | 8 |
void * | none defined | not defined by ISO C |
Why Void Pointer Arithmetic Is Not Allowed in Standard C
The last row of the table is the whole story. Scaling needs a size, and void has none. In standard C, adding to or subtracting from a void * is a constraint violation, so a strict compiler must reject it. The same reason forbids vp++, vp--, vp += n and vp - vp2 on generic pointers.
Same address, different step size
What GCC Does With void Pointer Arithmetic
GCC treats sizeof(void) as 1 as an extension, so arithmetic on a void * moves in single bytes. That makes the program below work by default, but it is not portable C.
#include <stdio.h>
int main(void)
{
int data[2] = {10, 20};
void *vp = data;
void *next = vp + 1; /* GNU extension, not standard C */
printf("step taken by vp + 1 : %td byte(s)\n", (char *)next - (char *)vp);
printf("sizeof(int) : %zu bytes\n", sizeof(int));
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o void_gnu ep_void_gnu_ext.c
./void_gnu
The compiler warns, but still builds:
progs/ep_void_gnu_ext.c: In function 'main':
progs/ep_void_gnu_ext.c:7:21: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
7 | void *next = vp + 1; /* GNU extension, not standard C */
| ^
And the program runs, proving the step is one byte even though the array holds 4-byte ints:
step taken by vp + 1 : 1 byte(s)
sizeof(int) : 4 bytes
Ask the compiler to enforce the standard with -pedantic-errors and the warning becomes a failure:
gcc -std=c11 -pedantic-errors -o void_gnu ep_void_gnu_ext.c
progs/ep_void_gnu_ext.c: In function 'main':
progs/ep_void_gnu_ext.c:7:21: error: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
7 | void *next = vp + 1; /* GNU extension, not standard C */
| ^
Do not rely on this. Code that depends on the byte-stepping extension breaks on compilers that follow ISO C strictly, and it is a classic source of bugs when a developer assumes the step is the element size. Static analysis tools used in safety-focused embedded projects flag it as well.
Correct Void Pointer Arithmetic: Two Methods
| Method | How it works | Best when |
|---|---|---|
| Cast to the real type, then add | (float *)vp + 1 steps by sizeof(float) | you know the element type |
| Cast to a byte pointer, scale yourself | (unsigned char *)vp + i * size | the element size arrives as a parameter |
Example 1: Walking a float array through a void pointer
#include <stdio.h>
int main(void)
{
float temps[4] = {21.5f, 22.0f, 22.5f, 23.0f};
const void *cursor = temps;
/* way 1: cast to the real type, add 1 -> moves by sizeof(float) */
for (int i = 0; i < 4; i++) {
printf("%.1f ", *(const float *)cursor);
cursor = (const float *)cursor + 1;
}
printf("\n");
/* way 2: do the byte math yourself through a char pointer */
cursor = temps;
for (int i = 0; i < 4; i++) {
printf("%.1f ", *(const float *)cursor);
cursor = (const char *)cursor + sizeof(float);
}
printf("\n");
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o void_walk ep_void_walk.c
./void_walk
21.5 22.0 22.5 23.0
21.5 22.0 22.5 23.0
Both loops print the same four readings. The first casts to const float * and adds 1, so the compiler multiplies by sizeof(float) for us. The second casts to const char * and adds sizeof(float) explicitly, doing the multiplication by hand. In both cases the cursor itself stays a generic const void *, and we convert only for the moment of the access or the step.
Old textbook style that no longer compiles
Some older books write a cast on the left of an assignment to advance a generic pointer. Modern C does not allow that, because the result of a cast is not an lvalue:
#include <stdio.h>
int main(void)
{
float temps[2] = {1.5f, 2.5f};
void *vp = temps;
(float *)vp = (float *)vp + 1; /* old textbook style: not valid C */
printf("%.1f\n", *(float *)vp);
return 0;
}
progs/bad_cast_lvalue.c: In function 'main':
progs/bad_cast_lvalue.c:8:17: error: lvalue required as left operand of assignment
8 | (float *)vp = (float *)vp + 1; /* old textbook style: not valid C */
| ^
Write the step on the right-hand side instead, exactly as the first loop above does: cursor = (const float *)cursor + 1;.
Generic Functions Built on Void Pointer Arithmetic
Now the payoff. A function that works for any element type cannot use vp + 1, because it does not know the type, but it can receive the element size as a parameter and step in bytes. Every generic C library routine, including qsort and bsearch, is built on this idea.
Element address = base + i * size
| Array | Element size | Offset of element 0 | Offset of element 1 | Offset of element 2 |
|---|---|---|---|---|
int codes[4] | 4 bytes | 0 | 4 | 8 |
double volts[3] | 8 bytes | 0 | 8 | 16 |
#include <stdio.h>
#include <string.h>
#include <stddef.h>
/* swap any two objects of 'size' bytes */
static void ep_swap(void *a, void *b, size_t size)
{
unsigned char tmp[16]; /* small demo buffer */
if (size > sizeof tmp) {
return;
}
memcpy(tmp, a, size);
memcpy(a, b, size);
memcpy(b, tmp, size);
}
/* visit every element of an array whose element type we do not know */
static void ep_foreach(const void *base, size_t count, size_t size,
void (*visit)(const void *elem))
{
const unsigned char *p = base; /* byte pointer: arithmetic is legal */
for (size_t i = 0; i < count; i++) {
visit(p + i * size);
}
printf("\n");
}
static void show_int(const void *e) { printf("%d ", *(const int *)e); }
static void show_double(const void *e) { printf("%.2f ", *(const double *)e); }
int main(void)
{
int codes[4] = {11, 22, 33, 44};
double volts[3] = {1.25, 3.30, 5.00};
int x = 7, y = 9;
ep_foreach(codes, 4, sizeof codes[0], show_int);
ep_foreach(volts, 3, sizeof volts[0], show_double);
printf("before swap: x=%d y=%d\n", x, y);
ep_swap(&x, &y, sizeof x);
printf("after swap: x=%d y=%d\n", x, y);
ep_swap(&volts[0], &volts[2], sizeof volts[0]);
ep_foreach(volts, 3, sizeof volts[0], show_double);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o void_generic ep_void_generic.c
./void_generic
11 22 33 44
1.25 3.30 5.00
before swap: x=7 y=9
after swap: x=9 y=7
5.00 3.30 1.25
Two helpers do all the work. ep_foreach converts the base address to const unsigned char *, which is a byte pointer, and visits element i at p + i * size. It hands each element’s address to a callback that knows the real type. ep_swap copies bytes through a temporary buffer with memcpy, so it can exchange two ints, two doubles or any other pair of equal-sized objects. The same ep_foreach printed an int array and a double array, and ep_swap exchanged x and y and then the first and last voltages.
Where This Matters in C Programming for Embedded Systems
- Protocol parsers: advance a byte pointer through a received frame, field by field.
- Ring buffers and queues: a generic queue stores items of any size in one byte array and finds slot
iatbase + i * item_size. - Container and driver libraries: a single implementation serves several structure types.
- Sorting and searching: the standard
qsortandbsearchtakevoid *and an element size for exactly this reason.
Common Mistakes With Void Pointer Arithmetic
| Mistake | What happens | Fix |
|---|---|---|
Writing vp + 1 and expecting an element step | under GCC it moves one byte, so you land in the middle of an element | cast to the real type, or multiply by the element size yourself |
Using a byte pointer but adding i instead of i * size | every element after the first is misread | always scale the index |
Casting the stepped byte pointer to uint32_t * at an odd address | misaligned access, a fault on some cores | copy the bytes with memcpy into a properly typed variable |
Forgetting that i * size can overflow | the address wraps and points to unrelated memory | validate count and size before looping |
Writing a cast on the left of = | compile error: lvalue required | put the cast on the right and assign to the pointer variable |
Alignment on microcontrollers. Some embedded cores raise a fault when a multi-byte value is loaded from an address that is not a multiple of its size. If a byte buffer holds packed data, read each field with memcpy instead of casting the pointer.
Best Practices, Performance and Security
- Build with
-pedanticor-Wpointer-arithso accidental void pointer arithmetic is reported immediately. - Step through generic memory with
unsigned char *. Character types may alias any object, so the access is always legal. - Pass
countandsizetogether, and check them against the buffer capacity before the first access. - Byte-at-a-time loops are portable but slow for large blocks. For bulk copies call
memcpy, which the library can optimize. - Keep generic code small and well tested. One unchecked size in a shared helper becomes a vulnerability in every caller.
Summary and Key Takeaways
Key takeaways
- Typed pointer arithmetic scales by
sizeofof the pointed-to type;voidhas no size, so ISO C forbids void pointer arithmetic. - GCC allows it as an extension and steps one byte, but the code is not portable.
- To advance a generic pointer, cast to the real type and add, or cast to a byte pointer and multiply by the element size.
- Place the cast on the right of the assignment; a cast is not an lvalue.
- Generic helpers such as
ep_foreachandep_swapuse element size and byte pointers. - Watch alignment, overflow and size validation whenever you convert a byte pointer back to a typed one.
Conclusion
Void pointer arithmetic looks like a small syntax question, but it teaches the core rule of C memory access: the type of a pointer decides how far it moves and how its target is read. Once you internalize that, generic code stops being mysterious. You know to avoid the byte-stepping extension, to cast on the right-hand side, to scale by the element size, and to guard alignment and overflow. In the next lecture of this free embedded C course we use all of this to ask the system for memory at run time with malloc.
Frequently Asked Questions
Can you do pointer arithmetic on a void pointer in C?
Not in standard C. The size of void is undefined, so the compiler cannot scale the step. GCC allows it as an extension and treats the step as one byte, but that is not portable.
What happens if I write vp + 1 in GCC?
The pointer advances by one byte, as if sizeof(void) were 1. With -pedantic you get a warning, and with -pedantic-errors the build fails.
How do I increment a void pointer correctly?
Cast it to the real type and add: p = (float *)p + 1;. Or cast to a byte pointer and add a scaled offset: p = (char *)p + sizeof(float);.
Why do generic functions pass an element size?
Because the function cannot know the type behind a void *. With the size it can compute each element address as base + i * size using a byte pointer.
Which pointer type is safest for stepping through raw memory?
unsigned char *. Character types may legally access any object, and the step size of one byte makes the arithmetic explicit.
Can I subtract two void pointers?
Not in standard C. Cast both to char * first to get a byte distance, or to the real type to get an element count.
Why does my cast on the left of an assignment fail?
A cast produces a value, not an lvalue, so it cannot be assigned to. Assign to the pointer variable itself and put the cast on the right: vp = (float *)vp + 1;.
Next up: dynamic memory allocation
Generic pointers are the doorway to run-time memory. In the next lecture of our free embedded C course we ask the heap for memory with malloc.

2 Comments