Structures and casting in C

前端 未结 8 1515
野性不改
野性不改 2020-12-16 02:07

I was wondering:

If I have structure definitions, for example, like this:

struct Base {
  int foo;
};

struct Derived {
  int foo; // int foo is comm         


        
8条回答
  •  没有蜡笔的小新
    2020-12-16 02:49

    You should do

    struct Base {
      int foo;
    };
    
    struct Derived {
      struct Base base;
      char *bar;
    };
    

    to avoid breaking strict aliasing; it is a common misconception that C allows arbitrary casts of pointer types: although it will work as expected in most implementations, it's non-standard.

    This also avoids any alignment incompatibilities due to usage of pragma directives.

提交回复
热议问题