Neet33
Neet33

Reputation: 281

Understanding memory structure when casting pointers of different sizes of structs

struct A //size 4
struct B //size 8

unsigned char *mem; 
A *a=(A *)mem; 
B *b=(B *)a+sizeof(A); //I want address of b to be 4

Please correct me if I'm wrong:

lets say address of mem is 0, if so

address of a is 0, if so

address of b is 0+8*4 //0+sizeof(A)*sizeof(B)

If that's correct How I cast 'pointer to struct A' to 'pointer to struct B' then add to the address a number. (commented in the code)

Thanks.

Upvotes: 0

Views: 50

Answers (1)

toth
toth

Reputation: 2552

You are correct that if p is of type T*, then the address p+n is the address p plus n*sizeof(T).

If pa is of type A* to cast it to type B* you simply write B * pb = (B*)pa;.

If you want to advance it by a given number of bytes n, you can cast to char* first, advance (since sizeof(char)=1), and then cast of to B*. I.e., B* pb = (B*)( ((char*)pa) +n);

However, except for very special circumstances, you shouldn't really need to do something like this, since it is very easy to get garbage as a result.

Whatever it is that you are actually trying to do, there is probably a better and less error prone way.

Upvotes: 2

Related Questions