Tuesday, November 25, 2008

C/C++ Pointer Arithmetic notes

when you say:
int *p = ...
p++; /* means p = p + sizeof(int) */

what about void pointers?
void *p = ...
p++; /* compiler error */

as the size of void is unknown.

also,

(int*)pvoid++; // will not compile because the increment operator has higher Precedence than casting
i.e: the casting is for the increment result. so, you are still incrementing a void pointer.

to increment a void pointer you can use

pv = (void*)(((int*) pv)+1);
to increment the void pointer as integer pointer. but, the increment will be with the sizeof(int)

example:
int x[2] = {5,6};
int *p = x;
void *pv = (void*)p ;

pv = (void*)(((int*) pv)+1);

printf("%d\n",*(int*)pv);

or simply you can define a pointer to integer and increment it.
example:

int *p = (int*) pVoid;
p++;