0
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.

Neet33
  • 241
  • 1
  • 5
  • 17
  • Recommended reading: [what-is-the-strict-aliasing-rule](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) – user3386109 Jul 22 '15 at 01:23

1 Answers1

2

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.

toth
  • 2,519
  • 1
  • 15
  • 23
  • I'm actually trying to parse a binary file, so I need to get to some position then cast it to some struct then get to other position then cast it to different struct. Is there a way that can do that better? – Neet33 Jul 22 '15 at 01:28
  • It would be preferable to just have `char *` pointer that you advance and cast to the different struct pointer types as required, as opposed to converting between different struct pointers. I admit that does not gain you a whole bunch, but I would argue it is a bit cleaner. – toth Jul 22 '15 at 01:33
  • @Neet33 Also, if the layout of your binary file is fixed in advance (i.e., always two struct As, followed by a struct B, etc), you could just define a bigger packed struct that contains these structs and read into that. You can then let the compiler do all of the addressing for you. – toth Jul 22 '15 at 01:35
  • Are you aware of the strict aliasing rule? You are just violating it. – too honest for this site Jul 22 '15 at 02:26
  • You mean the answer poster is violating it? – Neet33 Jul 22 '15 at 03:30