Take the following C code as an example:
char buffer1[5];
int* ret;
printf("Buffer1 is: %x\n", (int*)buffer1);
ret = (int*)buffer1 + 12;
printf("Ret is: %x\n", ret);
I just want to add 12 bytes to buffer1 and store it in ret. This is obviously wrong, but I don’t know how to properly add hex address in C. Any help is appreciated.
If you want to add 12 bytes, you need a data type that work on byte boundaries, like a
char *. Now you may think you’re doing that (buffer1decays to achar *) but, because a cast binds more tightly than an addition,(int*)buffer1 + 12actually means((int*)buffer1) + 12rather than(int*)(buffer1 + 12).And the problem with adding 12 to an
int *is that it scales the addition. If yourintis four bytes, adding 12 to it will actually add 48 bytes.If you change the assignment line to:
you will find that the addition happens to
buffer1so will not be scaled, then the cast to anint *will operate on that value.I should mention of course that dereferencing the resultant pointer is probably not a good idea since it will be beyond the bounds of the actual array.
I’ll also suggest that
%pis probably a better format string to use for pointers.