I'm looking through my textbook and I'm a little confused about some of the code in there. In one part, they are performing pointer arithmetic in the following way:
void* bp;
...
bp = (void*)((char*)(bp)+16);
...
But later on, they do the following:
void* bp;
...
bp = bp+16;
...
I feel like they should be two different things but they are treating it like the same thing. I feel this way because, for example, if you were to do an array access (for an integer array for example),you would do the following
int* a = malloc(n*sizeof(int));
...
q = *(a+1);
...
in this case, aren't I accessing the next 4 bytes in the integer array and not the next byte?
Similarly, I feel that if I have void* a
, then *(a+1)
should be the next 4 bytes...
Or is this not the case?
It's a slip-up. Arithmetic on void *
is not defined by the standard, but some compilers offer it as an extension, behaving the same as char *
for arithmetic. The second is formally not valid C, but slipped through presumably out of (bad) habit.