如果您有一个数组 DIM2[X,Y],其维度为 Xn 和 Yn,您也可以将其(如您所说)表示为一维数组。
A[x,y] 然后会被映射到 DIM1[x + y * Xn]
DIM1 必须有大小 (Xn * Yn)
具有维度 Xn,Yn,Zn 的 3 维数组 B[] 可以以相同的方式映射:
B[x,y,z] 将映射到 DIM1 [ x + y * Xn + z * Xn * Yn],DIM1 必须能够容纳 (Xn * Yn * Zn) 个项目,
B[x,y,z,a] 将映射到 DIM1 [ x + y * Xn + z * Xn * Yn + a * Xn * Yn *
锌]
等等
对于一般的 N 维数组,最好使用递归,其中 100 维数组是 99 维数组的数组。如果所有维度都具有相同的大小,那将相对简单(编写它,我还提到递归可以很容易地展开为一个简单的 for 循环,在下面找到它)
#include <stdio.h>
#include <math.h>
#include <malloc.h>
#define max_depth 5 /* 5 dimensions */
#define size 10 /* array[10] of array */
// recursive part, do not use this one
int _getValue( int *base, int offset, int current, int *coords) {
if (--current)
return _getValue (base + *coords*offset, offset/size, current, coords+1);
return base[*coords];
}
// recursive part, do not use this one
void _setValue( int *base, int offset, int current, int *coords, int newVal) {
if (--current)
_setValue (base + *coords*offset, offset/size, current, coords+1, newVal);
base[*coords]=newVal;
}
// getValue: read item
int getValue( int *base, int *coords) {
int offset=pow( size, max_depth-1); /* amount of ints to skip for first dimension */
return (_getValue (base, offset, max_depth, coords));
}
// setValue: set an item
void setValue( int *base, int *coords, int newVal) {
int offset=pow( size, max_depth-1);
_setValue (base, offset, max_depth, coords, newVal);
}
int main() {
int items_needed = pow( size, max_depth);
printf ("allocating room for %i items\n", items_needed);
int *dataholder = (int *) malloc(items_needed*sizeof(int));
if (!dataholder) {
fprintf (stderr,"out of memory\n");
return 1;
}
int coords1[5] = { 3,1,2,1,1 }; // access member [3,1,2,1,1]
setValue(dataholder, coords1, 4711);
int coords2[5] = { 3,1,0,4,2 };
int x = getValue(dataholder, coords2);
int coords3[5] = { 9,7,5,3,9 };
/* or: access without recursion: */
int i, posX = 0; // position of the wanted integer
int skip = pow( size, max_depth-1); // amount of integers to be skipped for "pick"ing array
for (i=0;i<max_depth; i++) {
posX += coords3[i] * skip; // use array according to current coordinate
skip /= size; // calculate next dimension's size
}
x = dataholder[posX];
return x;
}