Next: , Previous: Fixed-size Arrays in C, Up: Multi-dimensional Array Format


3.2.4 Dynamic Arrays in C

We recommend allocating most arrays dynamically, with fftw_malloc. This isn't too hard to do, although it is not as straightforward for multi-dimensional arrays as it is for one-dimensional arrays.

Creating the array is simple: using a dynamic-allocation routine like fftw_malloc, allocate an array big enough to store N fftw_complex values (for a complex DFT), where N is the product of the sizes of the array dimensions (i.e. the total number of complex values in the array). For example, here is code to allocate a 5 × 12 × 27 rank-3 array:

     fftw_complex *an_array;
     an_array = (fftw_complex*) fftw_malloc(5*12*27 * sizeof(fftw_complex));

Accessing the array elements, however, is more tricky—you can't simply use multiple applications of the ‘[]’ operator like you could for fixed-size arrays. Instead, you have to explicitly compute the offset into the array using the formula given earlier for row-major arrays. For example, to reference the (i,j,k)-th element of the array allocated above, you would use the expression an_array[k + 27 * (j + 12 * i)].

This pain can be alleviated somewhat by defining appropriate macros, or, in C++, creating a class and overloading the ‘()’ operator. The recent C99 standard provides a way to reinterpret the dynamic array as a “variable-length” multi-dimensional array amenable to ‘[]’, but this feature is not yet widely supported by compilers.