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