且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

传递三维数组作为参数传递给C中的函数

更新时间:2022-11-23 15:38:09

  1. 您不能省略类型
  2. 您可以省略数组
  3. 只有第一个维度

  INT sum3darray(一[] [] [],大小);
 

  INT sum3darray(INT A [] [3] [3],诠释大小);
 

  INT sum3darray(INT(*一)[3] [3],诠释大小);
 

正如刚才@CoolGuy,你可以省略原型的参数的名称:

  INT sum3darray(INT(*一)[3] [3],诠释大小);
 

可以写成

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

另一种方式来处理多维数组(如果你不知道事先尺寸)正在使用VLA的(谢谢你米Oehm)或手动压平的数组,的看看

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:

#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?

  1. You can not omit the types
  2. You can omit only the first dimension of an array


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:

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.