Passing 3D array as parameter to a function in C

人走茶凉 提交于 2019-12-10 21:53:37

问题


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:


  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.



来源:https://stackoverflow.com/questions/29605133/passing-3d-array-as-parameter-to-a-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!