title: In C, does the meaning of A[i][j] depend on how A is declared?
body: <p>Suppose I have a two-dimensional array <code>grid</code> declared as <code>double grid[5][5]</code>. It is my understanding that the following statements are true:</p>
  
  <ul>
  <li>when <code>grid</code> is declared, a contiguous block of memory is allocated for 5*5 doubles, no more no less;</li>
  <li>when an element of the array is accessed with the notation <code>grid[i][j]</code>, this piece of code is actually interpreted as <code>*(grid+(i*5+j))</code>.</li>
  </ul>
  
  <p>On the other hand, I know I can also store the same matrix as an array of pointers, by writing something like:</p>
  
  <pre><code>double ** grid;
  grid = (double**)malloc(sizeof(double*)*5);
  for (i=0; i&lt;5; i++)
     grid[i] = (double*)malloc(sizeof(double)*5);
  </code></pre>
  
  <p>and I actually have a code which does that. The problem is that it then proceeds to access the elements of <code>grid</code> just like before, with the double subscript notation. Is this case different? In this case, is <code>grid[i][j]</code> converted to <code>*(*(grid+i)+j)</code>, i.e. to a double dereferenciation? That's the only way I can see it happen correctly.</p>
  
  <p>(This question probably stems from my (lack of) understanding of the relationship between pointer and array types in C...)</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Ok, let's see if I got this straight:</p>
  
  <ul>
  <li><code>grid[i][j]</code> is always converted to <code>*(*(grid+i)+j)</code>;</li>
  <li>this expression is indeed calculated differently in the two cases, because, as Jim states in his answer, pointer arithmetic takes into account the size of the type pointed to; nevertheless, the correct element is fetched in both cases;</li>
  <li><em>if and only if "grid" is a 2D array</em>, this expression is further optimized to <code>*( (double*)grid + (i*5+j) )</code>, which is possible because the compiler knows that any <code>grid[i]</code> is actually an array starting at location <code>grid+i*5</code>.</li>
  </ul>
  
  <p>But this leaves me with an inescapable conclusion: for a 2D array, if I set <code>i=j=0</code>, then I have that <code>**grid == *((double*)grid)</code>. Is this correct?</p>