Increment void pointer by one byte? by two?

C++CPointers

C++ Problem Overview


I have a void pointer called ptr. I want to increment this value by a number of bytes. Is there a way to do this?

Please note that I want to do this in-place without creating any more variables.

Could I do something like ptr = (void *)(++((char *) ptr)); ?

C++ Solutions


Solution 1 - C++

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 - C++

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 - C++

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 - C++

You can do:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam SView Question on Stackoverflow
Solution 1 - C++James McNellisView Answer on Stackoverflow
Solution 2 - C++Alok SaveView Answer on Stackoverflow
Solution 3 - C++tdammersView Answer on Stackoverflow
Solution 4 - C++EyalShView Answer on Stackoverflow