title: Efficiency: arrays vs pointers
body: <p>Memory access through pointers is said to be more efficient than memory access through an array.  I am learning C and the above is stated in K&amp;R. Specifically they say</p>
  
  <blockquote>
    <p>Any operation that can be achieved by array subscripting can also be done with pointers. The pointer version will in general be faster</p>
  </blockquote>
  
  <p>I dis-assembled the following code using visual C++.(Mine is a 686 processor. I have disabled all optimizations.)</p>
  
  <pre><code>int a[10], *p = a, temp;
  
  void foo()
  {
      temp = a[0];
      temp = *p;
  }
  </code></pre>
  
  <p>To my surprise I see that memory access through a pointer takes 3 instructions to the two taken by memory access through an array. Below is the corresponding code.</p>
  
  <pre><code>; 5    : temp = a[0];
  
      mov eax, DWORD PTR _a
      mov DWORD PTR _temp, eax
  
  ; 6    : temp = *p;
  
      mov eax, DWORD PTR _p
      mov ecx, DWORD PTR [eax]
      mov DWORD PTR _temp, ecx
  </code></pre>
  
  <p>Please help me understand. What am I missing here??</p>
  
  <hr>
  
  <p>As pointed out by many answers and comments I had used a compile time constant as the array index thus making it arguably easier for the access through an array. Below is the assembly code with a variable as the index. I now have equal number of instructions for access through pointer and arrays. My broader questions still holds good. The memory access through a pointer is not lending itself as being more efficient.</p>
  
  <pre><code>; 7    :        temp = a[i];
  
      mov eax, DWORD PTR _i
      mov ecx, DWORD PTR _a[eax*4]
      mov DWORD PTR _temp, ecx
  
  ; 8    : 
  ; 9    :    
  ; 10   :        temp = *p;
  
      mov eax, DWORD PTR _p
      mov ecx, DWORD PTR [eax]
      mov DWORD PTR _temp, ecx
  </code></pre>