Chris@10: Chris@10:
Chris@10:Chris@10: Next: Dynamic Arrays in C-The Wrong Way, Chris@10: Previous: Fixed-size Arrays in C, Chris@10: Up: Multi-dimensional Array Format Chris@10:
We recommend allocating most arrays dynamically, with
Chris@10: fftw_malloc
. This isn't too hard to do, although it is not as
Chris@10: straightforward for multi-dimensional arrays as it is for
Chris@10: one-dimensional arrays.
Chris@10:
Chris@10:
Creating the array is simple: using a dynamic-allocation routine like
Chris@10: fftw_malloc
, allocate an array big enough to store N
Chris@10: fftw_complex
values (for a complex DFT), where N is the product
Chris@10: of the sizes of the array dimensions (i.e. the total number of complex
Chris@10: values in the array). For example, here is code to allocate a
Chris@10: 5 × 12 × 27 rank-3 array:
Chris@10:
Chris@10:
fftw_complex *an_array; Chris@10: an_array = (fftw_complex*) fftw_malloc(5*12*27 * sizeof(fftw_complex)); Chris@10:Chris@10:
Accessing the array elements, however, is more tricky—you can't
Chris@10: simply use multiple applications of the ‘[]’ operator like you
Chris@10: could for fixed-size arrays. Instead, you have to explicitly compute
Chris@10: the offset into the array using the formula given earlier for
Chris@10: row-major arrays. For example, to reference the (i,j,k)-th
Chris@10: element of the array allocated above, you would use the expression
Chris@10: an_array[k + 27 * (j + 12 * i)]
.
Chris@10:
Chris@10:
This pain can be alleviated somewhat by defining appropriate macros, Chris@10: or, in C++, creating a class and overloading the ‘()’ operator. Chris@10: The recent C99 standard provides a way to reinterpret the dynamic Chris@10: array as a “variable-length” multi-dimensional array amenable to Chris@10: ‘[]’, but this feature is not yet widely supported by compilers. Chris@10: Chris@10: Chris@10: Chris@10: Chris@10: