title: Output Explanation of this program in C?
body: <p>I have this program in C:</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
  
    int i=300;
    char *ptr = &amp;i;
    *++ptr=2;
    printf("%d",i);
    return 0;
  }
  </code></pre>
  
  <p>The output is 556 on little endian.</p>
  
  <p>I tried to understand the output. Here is my explanation.</p>
  
  <p><strong>Question is Will the answer remains the same in the big endian machine?</strong></p>
  
  <p>i = 300;
  => i = 100101100 //in binary in word format => B B Hb 0001 00101100 where B = Byte and Hb = Half Byte</p>
  
  <p>(A)=> in memory (assuming it is Little endian))</p>
  
  <pre><code>0x12345678 - 1100 - 0010 ( Is this correct for little endian)
  
  0x12345679 - 0001 - 0000
  
  0x1234567a - 0000 - 0000
  
  0x1234567b - 0000 - 0000
  </code></pre>
  
  <p>0x1234567c - Location of next intezer(location of ptr++ or ptr + 1 where ptr is an intezer pointer as ptr is of type int => on doing ++ptr it will increment by 4 byte(<strong>size of int</strong>))</p>
  
  <p>when </p>
  
  <p>(B)we do char *ptr = &i; 
  ptr will become of type char => on doing ++ptr it will increment by 1 byte(<strong>size of char</strong>)
  so on doing ++ptr it will jump to location -> 0x12345679 (which has 0001 - 0000)
  now we are doing 
  <em>++ptr = 2
  => 0x12345679 will be overwritten by 2 => 0x12345679 will have 00</em>*10** - 0000 instead of 000*<em>1</em>* - 0000</p>
  
  <p>so the new memory content will look like this : </p>
  
  <p>(C)</p>
  
  <pre><code>0x12345678 - 1100 - 0010
  
  0x12345679 - 0010 - 0000
  
  0x1234567a - 0000 - 0000
  
  0x1234567b - 0000 - 0000
  </code></pre>
  
  <p>which is equivalent to => B B Hb 0010 00101100 where B = Byte and Hb = Half Byte</p>
  
  <p>Is my reasoning correct?Is there any other short method for this?
  Rgds,
  Softy</p>