title: Implementing a 3D array as a pointer to a variable length array
body: <p>I just learned about <strong>variable length arrays</strong> in C, and somebody suggested to me that I can realize a 3D array-like object in C simply as a pointer to a variable length array. A simple implementation would look as follows:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main( int argc, char *argv[] ) {
  
      size_t  ii, jj, kk,
              Nx, Ny, Nz;
  
      Nx  = 2;
      Ny  = 3;
      Nz  = 4;
  
      // initialize 3D array as pointer to a variable length array
      double (*arr3d)[Ny][Nz] = calloc(Nx, sizeof *arr3d);
  
      for( ii=0 ; ii&lt;Nx ; ++ii )
          for( jj=0 ; jj&lt;Ny ; ++jj )
              for( kk=0 ; kk&lt;Nz ; ++kk )
                  printf( &quot;arr3d[%ld,%ld,%ld] = %f, address = %p\n&quot;,
                      ii, jj, kk, arr3d[ii][jj][kk], &amp;arr3d[ii][jj][kk] );
  
      free(arr3d);
      return 0;
  
  }
  </code></pre>
  <p>In my understanding, one advantage (besides of the one-line implementation) is that <code>arr3d</code> can be simply passed to a function,</p>
  <pre><code>int doSomething( size_t dim1, size_t dim2, size_t dim3, double arr3d[dim1][dim2][dim3] );
  </code></pre>
  <p>by calling this function in the <code>main</code> function as follows:</p>
  <pre><code>doSomething( Nx, Ny, Nz, arr3d );
  </code></pre>
  <p>My question now, is this a valid implementation of a 3D array-like object or will I run into some trouble ? Note that in the actual case, the dimensions are larger by roughly a factor of 1000 each.</p>