Let’s say you have:
void *p = // something;
int size = 10;
*((char *)p + 8) = size ^ 1;
I know this looks like really random logic, but I was wondering if it would still do as intended. I am trying to place the entirety of “size ^ 1” at the address pointed to by “p + 8” when p is casted to a char. Basically what I am asking is, is it any different from:
*((int *)p + 2) = size ^ 1;
Also, what would happen if I had chosen to increment the pointers by 3, for example:
*((char *)p + 3) = size ^ 1;
or (I know this isn’t equivalent to all the others, but want to see if this is right):
*((int *)p + 3) = size ^ 1;
When you derefence a
char *pointer, you are referring to a singlecharobject. In this way, it is very similar to:That is, the resulting value (in this case, 11) is converted to type
charand then stored at the location(char *)p + 8(the 9thcharobject pointed to byp).So yes, it is quite different from:
The latter line modifies an entire
intobject, of sizesizeof(int), and the object modified is the 3rdintobject pointed to byp.If we imagine that you have a little-endian system with
sizeof(int) == 4, then your four examples will modify the memory pointed to bypin the following ways:1.
2.
3.
4.