0

I know how to do pointer arithmetic using arrays, but how do I do pointer arithmetic without them?

For my current assignment I have a void pointer to a memory address. I have a size_t which is storing a size in megabytes.

I am trying to add the half of the megabyte size to the pointer to find a memory address x/2 megabytes away from the pointer.

So

void *ptr = malloc(size_t x)    
void *ptr2 = ptr+x/2;

but the compiler says these datatypes are incompatible. what is the right syntax to do this?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • `malloc(size_t x)` this won't compile. – Sourav Ghosh Sep 25 '15 at 22:09
  • sorry, this is more of skeleton code. the initial pointer is given to me, and is linked the start of an area of memory given by malloc. I want to traverse this memory and make a pointer halfway through it, or half the size of x. – Adam Reb Alloy Sep 25 '15 at 22:10
  • the compiler gives me an error during the second operation - when I try to add a size in megabtyes to a void pointer. – Adam Reb Alloy Sep 25 '15 at 22:11
  • It is meaningless to do arithmetic on void pointers, which is why the standard (and your compiler) disallows it. Some compilers do allow it as an extension, in which case they treat the `void*` as a `char*`. You should do this explicitly. – Jon Sep 25 '15 at 22:11

1 Answers1

4

You should not be doing pointer arithmetic on void pointers. If you just want to increment the pointer by bytes count, you need to cast the pointer to char * and then apply pointer arithmetic on that.

Note: Arithmetic operation on void pointer is not standard C, though some compiler may support this as a compiler extension, but you better do not rely on that.

A detailed explanation on the same can be found here.


If it is possible, you can avoid the issue of void pointer arithmetic by changing the data type of ptr to char * (or simmilar). The void pointer returned by malloc() will be automatically and properly casted to the data type of ptr upon assignment, and then you can perform arithmetic operation on ptr, keeping in mind the size of the datatype.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261