title: Casting double array to a struct of doubles
body: <p>Is it OK to cast a double array to a struct made of doubles?</p>
  
  <pre><code>struct A
  {
     double x;
     double y;
     double z;
  };
  
  int main (int argc , char ** argv)
  {
     double arr[3] = {1.0,2.0,3.0};
     A* a = static_cast&lt;A*&gt;(static_cast&lt;void*&gt;(arr));
     std::cout &lt;&lt; a-&gt;x &lt;&lt; " " &lt;&lt; a-&gt;y &lt;&lt; " " &lt;&lt; a-&gt;z &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>This prints <code>1 2 3</code>. But is it guaranteed to work every time with any compiler?</p>
  
  <p>EDIT: According to</p>
  
  <blockquote>
    <p>9.2.21: A pointer to a standard-layout struct object, suitably converted ? using a reinterpret_cast, points to its initial member (...) and vice versa. </p>
  </blockquote>
  
  <p>if I replace my code with</p>
  
  <pre><code>struct A
  {
    double &amp; x() { return data[0]; }
    double &amp; y() { return data[1]; }
    double &amp; z() { return data[2]; }
  private:
     double data[3];
  };
  
  int main (int, char **)
  {
     double arr[3] = {1.0,2.0,3.0};
     A* a = reinterpret_cast&lt;A*&gt;(arr);
     std::cout &lt;&lt; a-&gt;x() &lt;&lt; " " &lt;&lt; a-&gt;y() &lt;&lt; " " &lt;&lt; a-&gt;z() &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>then it is guaranteed to work. Correct? I understand that many people would not find this aesteticaly pleasing but there are advantages in working with a struct and not having to copy the input array data. I can define member functions in that struct to compute scalar and vector products, distances etc, that will make my code much easier to understand than if I work with arrays.</p>
  
  <p>How about</p>
  
  <pre><code>int main (int, char **)
  {
     double arr[6] = {1.0,2.0,3.0,4.0,5.0,6.0};
     A* a = reinterpret_cast&lt;A*&gt;(arr);
     std::cout &lt;&lt; a[0].x() &lt;&lt; " " &lt;&lt; a[0].y() &lt;&lt; " " &lt;&lt; a[0].z() &lt;&lt; "\n";
     std::cout &lt;&lt; a[1].x() &lt;&lt; " " &lt;&lt; a[1].y() &lt;&lt; " " &lt;&lt; a[1].z() &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>Is this also guaranteed to work or the compiler could put something AFTER the data members so that <code>sizeof(A) &gt; 3*sizeof(double)</code>? And is there any portable way to prevent the compiler from doing so?</p>