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

标签 c multidimensional-array casting c99 variable-length-array

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

如何将 globalArray 指针转换为可变长度数组(指针)并自然地使用它? 我认为 typedef 方法有帮助,但我仍然迷失方向。当前版本经过我的修改后可以编译并看起来可以工作。 Cast #1 和 Cast #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

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

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

最佳答案

这是我经过一番修改后得出的一种可能的类型转换解决方案。

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

关于C99 如何将简单指针转换为可变长度的多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46431130/

相关文章:

c# - 多维列表 C#

java - 具体类实现一个接口(interface)。稍后类型转换为接口(interface)。 JVM 如何识别 Typecasted 实例?

c - 使用十六进制数

c - 为什么 Eclipse 向我的 C 命令行参数添加单引号?

在 UNIX 中杀死父进程的所有子进程的 C/C++ 程序?

c - 解析符号链接(symbolic link)同时避免超时

c++ - 有 4 个括号的数组的维数是多少

c - MSP430 执行库

c - 为什么这段代码打印地址?

c++ - 检查引用上的静态转换