title: when cast pointer to point to a struct containing union
body: <p>I have problem with a struct containing union. Here is the problem:</p>
  
  <pre><code>typedef struct
  {
      unsigned char Type;                          
      union
      {
          unsigned char Length;
          unsigned __int16 Length2;
      }
      char Value[0];    
  } TLV_TUPLE, *PTLV_TUPLE;
  </code></pre>
  
  <p>If <code>Type == 0x40h</code>, I use <code>Length2</code>, otherwise use <code>Length</code>.</p>
  
  <p>I use this structure to read this file stream (In hex):</p>
  
  <p><code>FE 01 01 40 12 00 30 …</code></p>
  
  <p>Now the code:</p>
  
  <pre><code>unsigned char * m_pTLV;
  
  /*code here to  let m_pTLV points to the
    first byte of the file, that is, point to 'FE' */
  
  PTLV_TUPLE pTlv = (PTLV_TUPLE)m_pTLV; // cast m_pTLV to PTLV_TUPLE
  </code></pre>
  
  <p>Then as I check the value of pTlv with debugger, I see this:</p>
  
  <pre><code>pTlv-&gt;Type == FE
  pTlv-&gt;Length == 1
  pTlv-&gt;Length2 == 4001
  pTlv-&gt;Value == 12
  </code></pre>
  
  <p>Shouldn't <code>Length2</code> be <code>0x101</code> and <code>value</code> be <code>48</code>?</p>
  
  <p>machine is little endian.</p>
  
  <p>Please help me with this...</p>