title: struct packing: how to add struct members at the beginning?
body: <p>I'm implementing a binary tree in C89, and I'm trying to share common attributes among all node structs through composition. Thus I have the following code:</p>
  
  <pre class="lang-c prettyprint-override"><code>enum foo_type
  {
      FOO_TYPE_A,
      FOO_TYPE_B
  };
  
  struct foo {
      enum foo_type type;
  };
  
  struct foo_type_a {
      struct foo base;
      struct foo * ptr;
  };
  
  struct foo_type_b {
      struct foo base;
      char * text;
  };
  </code></pre>
  
  <p>I'm including a member of type <code>struct foo</code> in all struct definitions as their initial member in order to provide access to the value held by <code>enum foo_type</code> regardless of struct type.  To achieve this I'm expecting that a pointer to a structure object points to its initial member, but I'm not sure if this assumption holds in this case. With C99, the standard states the following (see ISO/IEC 9899:1999 6.7.2.1 §13)</p>
  
  <blockquote>
    <p>A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.</p>
  </blockquote>
  
  <p>Although all structs share a common <code>struct foo</code> object as their initial member, padding comes into play.  While <code>struct foo</code> only has a single member which is as <code>int</code> size, both <code>struct foo_type_a</code> and <code>struct foo_type_b</code> include pointer members, which in some cases increase the alignment and thus adds padding.</p>
  
  <p>So, considering this scenario, does the C programming language (C89 or any subsequent version) ensures that it's safe to access the value of <code>struct foo::type</code> through a pointer to an object, whether that object is of type <code>struct foo</code> or includes an object of type <code>struct foo</code> as its first member, such as <code>struct foo_type_a</code> or <code>struct foo_type_b</code>? </p>