5

I was thinking of writing a function that takes n parameters and returns an n-dimensional array using those parameters as the dimensions. Now i realize an one-d and 2d array is easy to implement with pointers. For 2d array the snippet would be something like (standard way) :

int** x;
int* temp;

x = (int**)malloc(m * sizeof(int*));
temp = (int*)malloc(m*n * sizeof(int));
for (int i = 0; i < m; i++) {
  x[i] = temp + (i * n);
}

where the array is of size m*n; But the problem lies how do we find the nested loop parameters for a n-dimensional array? Is there any way to optimize the code?

4

2 回答 2

11

这显示了如何创建 N 维数组以及如何索引其元素。这些提供了所需的基本机制。这是学生在学习时考虑的问题,但在实践中很少使用。通常有更好的方法来组织数据结构。此外,大多数有用的算法在它们如何遍历数据方面都有模式,因此最好构建以增量方式有效更新索引的代码,而不是从头开始重新计算它们,如下所示。

/*  Note:  For demonstration purposes only.  Depending on needs, other types
    might be used for indices and sizes, and the array type might be wrapped
    in an opaque struct rather than exposed as "int *".
*/


//  Create an array with N dimensions with sizes specified in D.
int *CreateArray(size_t N, size_t D[])
{
    //  Calculate size needed.
    size_t s = sizeof(int);
    for (size_t n = 0; n < N; ++n)
        s *= D[n];

    //  Allocate space.
    return malloc(s);
}

/*  Return a pointer to an element in an N-dimensional A array with sizes
    specified in D and indices to the particular element specified in I.
*/
int *Element(int *A, size_t N, size_t D[], size_t I[])
{
    //  Handle degenerate case.
    if (N == 0)
        return A;

    //  Map N-dimensional indices to one dimension.
    int index = I[0];
    for (size_t n = 1; n < N; ++n)
        index = index * D[n] + I[n];

    //  Return address of element.
    return &A[index];
}

使用示例:

//  Create a 3*3*7*7*9 array.
size_t Size[5] = { 3, 3, 7, 7, 9 };
int *Array = CreateArray(5, Size);

//  Set element [1][2][3][4][5] to -987.
*Element(Array, 5, Size, (size_t []) { 1, 2, 3, 4, 5 }) = -987;
于 2013-11-09T22:50:42.710 回答
2

我不喜欢使用多维数组,而是使用一维数组:

int* pArray = (int*) malloc(m * n * sizeof(int*));

// access pArray[a][b]
int result = pArray[a*m + b];
于 2013-11-09T22:43:04.463 回答