title: Two Dimensional Array Implementation Using Double Pointer
body: <p>Please consider the following code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define NUM_ARRAYS     4
  #define NUM_ELEMENTS   4
  #define INVALID_VAL   -1
  
  int main()
  {
     int index            = INVALID_VAL;
     int array_index      = INVALID_VAL;
     int **ptr            = NULL;
  
     ptr = malloc(sizeof(int*)*NUM_ARRAYS);
  
     if (!ptr)
     {
        printf ("\nMemory Allocation Failure !\n\n");
        exit (EXIT_FAILURE);
     }
  
     for (index=0; index&lt;NUM_ARRAYS; index++)
     {
        *(ptr+index) = malloc(sizeof(int)*NUM_ELEMENTS); 
  
        if (!*(ptr+index))
        {
           printf ("\nMemory Allocation Failure !\n");
           exit (EXIT_FAILURE);
        }
     }
  
     /* Fill Elements Into This 2-D Array */
     for (index=0; index&lt;NUM_ARRAYS; index++)
     {
        for (array_index = 0; array_index&lt;NUM_ELEMENTS; array_index++)
        {
           *(*(ptr+index)+array_index) = (array_index+1)*(index+1);
        }
     }
  
     /* Print Array Elements */
     for (index = 0; index&lt;NUM_ARRAYS; index++)
     {
        printf ("\nArray %d Elements:\n", index);
        for (array_index = 0; array_index&lt;NUM_ELEMENTS; array_index++)
        {
           printf (" %d ", *(*(ptr+index)+array_index));
        }
        printf ("\n\n");
     }
  
     return 0;
  }
  </code></pre>
  
  <p>There is no problem with my code. It works fine.</p>
  
  <pre><code>Output:
  
  Array 0 Elements:
   1  2  3  4 
  
  
  Array 1 Elements:
   2  4  6  8 
  
  
  Array 2 Elements:
   3  6  9  12 
  
  
  Array 3 Elements:
   4  8  12  16 
  </code></pre>
  
  <p>I have a question about pointer arithmetic:</p>
  
  <p><code>*(ptr+0)</code> = Pointer to COMPLETE BLOCK (First Array)<br>
  <code>*(ptr+1)</code> = Pointer to COMPLETE BLOCK (Second Array).</p>
  
  <p>But what is: <code>(*ptr+1)</code>?</p>
  
  <p>GDB Output:</p>
  
  <pre><code>(gdb) p *(*ptr+1)
  $1 = 2
  (gdb) p *(*ptr+2)
  $2 = 3
  (gdb) p *(*ptr+3)
  $3 = 4
  (gdb) p *(*ptr+4)
  $4 = 0
  </code></pre>
  
  <p>I am getting confused on this. Please provide me some explanation to resolve this doubt.</p>