marktani
marktani

Reputation: 7808

Casting and adding pointers to types of different size

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?

Upvotes: 3

Views: 1378

Answers (2)

Louis Ricci
Louis Ricci

Reputation: 21106

Rather than a specific question like this you should probably try to gain more understanding of the language itself (pointers, dereference etc) http://www.cplusplus.com/doc/tutorial/pointers/

Assigning a value to a pointer is like saying this pointer represents the memory at address (value).

int8_t * a = 1; // a is memory at address 1
int16_t *b = (int16_t*)(a + 1); // b is memory at address (a + 1)... 2
int32_t *c = (int32_t*)b + 2; // c is memory at address 2 + (2 * sizeof(int32_t))... 10

Upvotes: 2

glglgl
glglgl

Reputation: 91099

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 a is 1, it (misalignedly) points to the memory address 1. Then you add 1, so that it points to 2, and cast the result to fit into b.

After that, you bake b a uint32_t * and add 2, so effectively you add 2*4 and thus get make b point to 10 (0xA).

If you do the said changes, your a points to 1 (and 2, as it has 16 bits), adding 1 will make b point to 3 (and 4) (the cast is not needed there), and c will point to 3+2*4 = 11.

Upvotes: 3

Related Questions