除了最左边的维度之外,您需要在编译时定义所有维度.
#define DIM 5
void do_something(float array[][DIM][DIM])
{
array[0][0][0] = 0;
...
}
Run Code Online (Sandbox Code Playgroud)
typedef 是你的朋友.
#include <stdio.h>
typedef int dimension1[20]; /* define dimension1 as array of 20
elements of type int */
typedef dimension1 dimension2[10]; /* define dimension2 as array of 10
elements of type dimension1 */
int foo(dimension2 arr[], size_t siz);
int main(void) {
dimension2 dimension3[7] = {0}; /* declare dimension3 as an array of 7
elements of type dimension2 */
dimension3[4][3][2] = 9999;
dimension3[4][0][12] = 1;
dimension3[3][8][18] = 42;
printf("%d\n", foo(dimension3, 7));
return 0;
}
int foo(dimension2 arr[], size_t siz) {
int d1, d2, d3;
int retval = 0;
for (d3=0; d3<siz; d3++) {
for (d2=0; d2<sizeof *arr / sizeof **arr; d2++) {
for (d1=0; d1<sizeof **arr / sizeof ***arr; d1++) {
retval += arr[d3][d2][d1];
}
}
/* edit: previous answer used definite types for the sizeof argument */
//for (d2=0; d2<sizeof (dimension2) / sizeof (dimension1); d2++) {
// for (d1=0; d1<sizeof (dimension1) / sizeof (int); d1++) {
// retval += arr[d3][d2][d1];
// }
//}
}
return retval;
}
Run Code Online (Sandbox Code Playgroud)
编辑
我不喜欢使用明确的类型作为参数sizeof.
我添加了获取(子)数组大小而不直接指定其类型的方法,而是让编译器从对象定义中推断出正确的类型.
第二次编辑
正如Per Eckman所说, 类型定义"裸"阵列可能很危险.请注意,在上面的代码中,我没有将数组本身传递给函数foo.我正在传递一个指向"低级"数组的指针.
foo(),在上面的代码中,接受指向类型对象的指针dimension2.的dimension3对象是元素的数组dimension2类型,而不是一个对象dimension3类型(甚至没有定义).
但请记住Per Eckman的说明.