将3D数组作为参数传递给C中的函数

时间:2022-02-06 21:49:04

Im trying to write a function that sums the elements of a 3d array, however it keeps saying there is a problem with the lines where I pass the 3d array as a parameter. My code is as follows:

我试图编写一个对3d数组的元素求和的函数,但是它一直说我将3d数组作为参数传递的行存在问题。我的代码如下:

#include <stdio.h>

int sum3darray(a[][][], size);

main() {
    int check[3][3][3]={ 0 };
    int size=3;
    printf("The sum is %d\n",sum3darray(check,size));
}

int sum3darray(a[][][],size) {
    int i,j,k,sum=0;
        for(i=0;i<size;i++) {
            for(j=0;j<size;j++) {
                for(k=0;k<size;k++) {
                    printf("i=%d, j=%d,k=%d, checkijk=%d  ",i,j,k,check[i][j][k]);
                    sum+=check[i][j][k];
                    printf("sum=%d\n", sum);
                }
            }
        }
return(sum);
}

The compiler flags lines 3 and 11 as problems. Can anyone help?

编译器将第3行和第11行标记为问题。有人可以帮忙吗?

1 个解决方案

#1


3  

  1. You can not omit the types
  2. 您不能省略类型

  3. You can omit only the first dimension of an array
  4. 您只能省略数组的第一个维度


int sum3darray(a[][][], size);

should be

int sum3darray(int a[][3][3], int size);

or

int sum3darray(int (*a)[3][3], int size);

As pointed out by @CoolGuy, you can omit the name of the parameters in prototypes:

正如@CoolGuy所指出的,您可以省略原型中参数的名称:

int sum3darray(int (*a)[3][3], int size);

can be written as

可写成

int sum3darray(int (*)[3][3], int);

Another way to deal with multidimensional arrays (if you don't know the sizes beforehand) is using VLA's (thank you M Oehm) or flattening the array manually, take a look.

另一种处理多维数组的方法(如果你事先不知道大小)是使用VLA(谢谢M Oehm)或手动展平数组,看一看。

#1


3  

  1. You can not omit the types
  2. 您不能省略类型

  3. You can omit only the first dimension of an array
  4. 您只能省略数组的第一个维度


int sum3darray(a[][][], size);

should be

int sum3darray(int a[][3][3], int size);

or

int sum3darray(int (*a)[3][3], int size);

As pointed out by @CoolGuy, you can omit the name of the parameters in prototypes:

正如@CoolGuy所指出的,您可以省略原型中参数的名称:

int sum3darray(int (*a)[3][3], int size);

can be written as

可写成

int sum3darray(int (*)[3][3], int);

Another way to deal with multidimensional arrays (if you don't know the sizes beforehand) is using VLA's (thank you M Oehm) or flattening the array manually, take a look.

另一种处理多维数组的方法(如果你事先不知道大小)是使用VLA(谢谢M Oehm)或手动展平数组,看一看。