问题
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
- 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