Increment void pointer by one byte? by two?

Solution 1:

You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object.

You can, however, cast the pointer to a char*, do arithmetic on that pointer, and then convert it back to a void*:

void* p = /* get a pointer somehow */;

// In C++:
p = static_cast<char*>(p) + 1;

// In C:
p = (char*)p + 1;

Solution 2:

No arithmeatic operations can be done on void pointer.

The compiler doesn't know the size of the item(s) the void pointer is pointing to. You can cast the pointer to (char *) to do so.

In gcc there is an extension which treats the size of a void as 1. so one can use arithematic on a void* to add an offset in bytes, but using it would yield non-portable code.

Solution 3:

Just incrementing the void* does happen to work in gcc:

#include <stdlib.h>
#include <stdio.h>

int main() {
    int i[] = { 23, 42 };
    void* a = &i;
    void* b = a + 4;
    printf("%i\n", *((int*)b));
    return 0;
}

It's conceptually (and officially) wrong though, so you want to make it explicit: cast it to char* and then back.

void* a = get_me_a_pointer();
void* b = (void*)((char*)a + some_number);

This makes it obvious that you're increasing by a number of bytes.

Solution 4:

You can do:

++(*((char **)(&ptr)));