0

You can cast (pointers to) structs in C quite easily:

For example there is struct A:

typedef struct {
    int a;
    int b;
}A;

and a struct B:

typedef struct {
    A parent;
    int c;
}B;

Now if x is a pointer to a struct B, I could do the following:

A *a_struct = (A*) x;

Now I am asking if this is actual defined behaviour or if it is just 'random' that it works with (some) compilers (I tested it with gcc)

mame98
  • 1,271
  • 12
  • 26
  • 1
    Yes, it's defined behavior in *this specific case*. I'm in a cafeteria right now, so if you need searching this site to find the no-doubt several duplicates of this question, it may be awhile unless someone else beats me to it. – WhozCraig Jul 07 '16 at 19:15
  • 2
    This question seems to be about the same thing: [Does accessing the first field of a struct via a C cast violate strict aliasing?](http://stackoverflow.com/questions/9747010/does-accessing-the-first-field-of-a-struct-via-a-c-cast-violate-strict-aliasing) – Theodoros Chatzigiannakis Jul 07 '16 at 19:20
  • 1
    Why would you want to do that? To know that the cast is well defined you have to know that the source type is `B`. So why not just use `&X->parent` ? – Jens Gustedt Jul 07 '16 at 19:24
  • 1
    @JensGustedt think of something like an object system, where child 'classes' have their 'parent' as first property. This makes sure that a child class can still be used with functions expecting the parent class. And after a curtain number of children it is getting pretty confusing using `->parent`. Think of something like the 8th child, you would need: `X->parent->parent->parent->parent->parent->parent->parent->parent` (it looks a bit confusing) – mame98 Jul 07 '16 at 19:29

0 Answers0