繁体   English   中英

C99 如何将简单指针转换为可变长度的多维数组?

[英]C99 How to cast simple pointer to a multidimensional-array of variable length?

在我的函数体reduce()initialize(...)我想将数组globalArray作为一个三维数组globalArray ,其中的维度直到运行时才知道。

如何将globalArray指针转换为变长数组(指针)并自然使用? 我认为typedef方法有帮助,但我仍然迷失了方向。 在我的修补之后,这个当前版本可以编译并且似乎可以工作。 演员 #1 和演员 #2 是否尽可能清晰和安全?

#include <stdlib.h>
#include <stdio.h>

double * globalArray; /* working from a situation where the array is global, declared elsewhere */
int M, N, P; /*array dimensions not known until runtime */

double reduce();
double reduce()
{
    /* Here I want to re-interpret the one-dimensional globalArray into
       a multi-dimensional variable-length array so that compiler takes
       care of the indexing math for me.*/
    typedef double (*arr_t)[N][P];

    const arr_t castArray = (arr_t)globalArray;  /* Cast #1 */

    double sum=0.0;
    for (int i=0; i<M; i++)
        for (int j=0; j<N; j++)
            for (int k=0; k<P; k++)
                sum += castArray[i][j][k];
    return sum;
}

void initialize(int M, int N, int P, double threedimarray[M][N][P])
{
    for (int i=0; i<M; i++)
        for (int j=0; j<N; j++)
            for (int k=0; k<P; k++)
                threedimarray[i][j][k] = (double)(i*N*P + j*P + k);
}

int main(int argc, char **argv)
{
    M = 10; N=1000; P=200;
    globalArray = malloc( M*N*P* sizeof(double) );

    typedef double (*arr_t)[N][P];
    initialize(M, N, P, (arr_t)globalArray); /* Cast #2 */

    double result = reduce();
    printf("Reduced result: %f\n", result );
    return 0;
}

https://ideone.com/5Y8Q64

我正在修改一个大型程序的一小部分。 显然有比程序范围数组指针更好的设计方法。 就是这样。 从自我记录的角度来看,如果解决方案不抛弃我们“知道”领先维度 (M) 的范围这一事实,那就太好了。

与函数参数声明相关的类似 SO 问题很有帮助,但我没有把我猜的点联系起来。 我决定在这里问,希望答案能传达给更多人。

这是我经过一些修补后得出的一种可能的铸造解决方案。

typedef double (*arr_t)[N][P];
arr_t castArray = (arr_t)globalArray;

/* Now castArray can be accessed by multi-dimensional index notation */
castArray[i][j][k] = 3.14;

缺点:

1) 不自行记录已知的前导维度长度M

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM