tags:

views:

140

answers:

4

Given a void pointer, if I want to make the void pointer point to x bytes ahead, how will this be best done? Is there a better way than casting to a char pointer?

+6  A: 

Is there a better way than casting to a char pointer?

No (except having a char * instead of a void * to begin with, so you don't have to cast it at all).

If this is not desirable or possible, then the only way is:

ptr = static_cast<char *>(ptr) + offset;

(Note: if you are doing this sort of stuff in C++, usually there is a much better solution. Unless you are an expert and you already ruled out every other alternative, I suggest you post a new question asking if there is a better way to do what you're trying to do!)

Krevan
As you suggested, i have posted another question herehttp://stackoverflow.com/questions/3378090/custom-memory-manager
aCuria
+1  A: 

Take a look at this question, and this question. To summarise, the answer is to cast to char * for arithmetic at a byte level.

Matt Joiner
+1  A: 

Given a void pointer, if I want to make the void pointer point to x bytes ahead, how will this be best done? Is there a better way than casting to a char pointer?

If you have a void*, you don't know that "x bytes ahead" is a valid address. You don't know that creating such a pointer won't crash your program.

And that is why it can't be done with void*.

You can only perform pointer arithmetics on pointers into an array. And if you have a pointer into an array, you know the type of the array, and can use the equivalent pointer type.

If you want some kind of abstract "byte pointer" (say, if you're implementing a memory pool and need to point to a specific offset into a buffer), you should use char* or unsigned char*, not void*.

jalf
+1  A: 

When doing pointer arithmetic compiler wants to take into account what it knows about the type that the pointer points to.

For example if you have a int *myint. Then these two statements actually do the same thing:

int a = *(myint+5);

and

int a = myint[5];

in this case myint+5 does not mean "the address of myint plus 5" but "the address of myint plus 5*sizeof(int))"

So in case of a void * the compiler can't make any assumptions what void * + 5 should mean. So before you use a void * it kind of forces you to specify how you want to use it.

Jaka