c - How to perform arithmetic operation on a void pointer -


this question has answer here:

i know how pointer arithmetic using arrays, how do pointer arithmetic without them?

for current assignment have void pointer memory address. have size_t storing size in megabytes.

i trying add half of megabyte size pointer find memory address x/2 megabytes away pointer.

so

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

but compiler says these datatypes incompatible. right syntax this?

you should not doing pointer arithmetic on void pointers. if want increment pointer bytes count, need cast pointer char * , apply pointer arithmetic on that.

note: arithmetic operation on void pointer not standard c, though compiler may support compiler extension, better not rely on that.

a detailed explanation on same can found here.


if possible, can avoid issue of void pointer arithmetic changing data type of ptr char * (or simmilar). void pointer returned malloc() automatically , casted data type of ptr upon assignment, , can perform arithmetic operation on ptr, keeping in mind size of datatype.


Comments