title: Cast struct pointer to another struct
body: <p>This code snippet prints the value <code>5</code>. I don't understand why.</p>
  <pre><code>#include &lt;stdio.h&gt;
  
  struct A
  {
      int x;
  };
  
  struct B
  {
      struct A a;
      int y;
  };
  
  void printA(struct A *a)
  {
      printf(&quot;A obj: %d\n&quot;, a-&gt;x);
  }
  
  int main(void)
  {
      struct B b = {
          {
              5
          },
          10
      };
      
      struct A *a = (struct A*)&amp;b;
      printA(a);
      
      printf(&quot;Done.\n&quot;);
      return 0;
  }
  </code></pre>
  <p>When I create <code>b</code>, a pointer to it would point to the data <code>{ {5}, 10 }</code>.</p>
  <p>When I cast <code>&amp;b</code> to <code>struct A*</code>, I'm assuring the compiler that this <code>struct A*</code> points to a struct of a single data element of data type <code>int</code>. Instead, I'm providing it a pointer to a struct of two data elements of data types <code>struct A</code>, <code>int</code>.</p>
  <p>Even if the second variable is ignored (since <code>struct A</code> has only one data member) I am still providing it a struct whose member is of data type <code>struct A</code>, not <code>int</code>.</p>
  <p>Thus, when I pass in <code>a</code> to <code>printA</code>, the line <code>a-&gt;x</code> is performed, essentially asking to access the first data element of <code>a</code>. The first data element of <code>a</code> is of data type <code>struct A</code>, which is a type mismatch due to the <code>%d</code> expecting a digit, not  a <code>struct A</code>.</p>
  <p>What exactly is happening here?</p>