Suppose I have following code snippet:
int8_t *a = 1;
int16_t *b = (int16_t*)(a + 1);
int32_t *c = (int32_t*)b + 2;
Then a = 1, b = 2, c = 10.
(Here I am not sure either, because I used printf() with %i and I got a warning about this.)
I am not quite sure how this works. I have some theories, but I prefer to read some documentation about it.
Can someone give me a key word to search for or explain the exact behaviour in this three cases to me? I wasn’t able to find information on this matter on SO or google for lack of a word to search for.
Will the output change when I type
int16_t *a = 1;
int32_t *b = (int16_t*)(a + 1);
int64_t *c = (int32_t*)b + 2;
instead?
I think your whole program is undefined behaviour, because I’m not sure if it is valid to put arbitrary values into pointer variables or to output them with
%i.That said, I think most environments are ok with it, so I think I can start to explain.
If
ais1, it (misalignedly) points to the memory address1.Then you add 1, so that it points to
2, and cast the result to fit intob.After that, you bake
bauint32_t *and add 2, so effectively you add2*4and thus get makebpoint to10 (0xA).If you do the said changes, your
apoints to1(and2, as it has 16 bits), adding1will makebpoint to3(and4) (the cast is not needed there), andcwill point to 3+2*4 = 11.