在C中通过引用传递的3d数组

Pon*_*nml 1 c arrays 3d reference

我正在使用一些x * y * z尺寸很大的图像立方体.

目前我一直在与他们打交道

int ***input = malloc(sizeof(int **)*(lines));
int d;
int i;
for(i = 0 ; i<lines ; i++) {
    input[i] = malloc(sizeof(int *)*bands);

    for(d = 0 ; d<bands ; d++) {
        *input[i][d] = malloc(sizeof(int)*(samples));
    }
}
Run Code Online (Sandbox Code Playgroud)

这对我来说很好,但现在我正在重写一些代码,并希望能够通过引用传递数组

我想这样做需要我通过这样的 foo(&input)

函数的位置如下:

foo(int ****input) {
    *input = malloc(sizeof(int **)*(lines));
    int d;
    int i;
    for(i = 0 ; i<lines ; i++) {
        *input[i] = malloc(sizeof(int *)*bands);

        for(d = 0 ; d<bands ; d++) {
            *input[i][d] = malloc(sizeof(int)*(samples));
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我似乎在进入第一个for(i...`循环后接收到seg故障.任何建议都会非常有帮助,谢谢.

Kaz*_*Kaz 5

当输入是指向3D矢量的指针时,这很好:

/* original */
input[i] = malloc(sizeof(int *)*bands);
Run Code Online (Sandbox Code Playgroud)

当输入变为int ****:指向向量指针的指针时,此更改不正确:

/* original */
*input[i] = malloc(sizeof(int *)*bands);
Run Code Online (Sandbox Code Playgroud)

你要:

/* original */
(*input)[i] = malloc(sizeof(int *)*bands);
Run Code Online (Sandbox Code Playgroud)

在C中, *x[y]意思是*(x[y]).

一个更简单的事情是使用局部变量:

void function(int ****pinput)
{
  int ***input = malloc(/* ... */);
  /*...code stays the same as before...*/
  *pinput = input; /* place it in the location specified by caller */
}
Run Code Online (Sandbox Code Playgroud)

另外,让我们对原作进行一些风格调整.(忽略缺少malloc故障检查):

int ***input = malloc(lines * sizeof *input);

int d;
int i;

for(i = 0 ; i<lines ; i++) {
    input[i] = malloc(bands * sizeof *input[0]);

    /* Noticed an error here: you have *input[i][d] = ... 
       but input[i][d] the pointer to the band;
       *input[i][d] is input[i][d][0]! */
    for(d = 0 ; d<bands ; d++)
        input[i][d] = malloc(samples * sizeof *input[0][0]);
}
Run Code Online (Sandbox Code Playgroud)

我刚刚拿出了一些不必要的括号,并改变了计算的大小,以便不是重复(int **)等,而是基于指定给它的指针表达式的类型.