这对我有用(评论解释了原因):
#include <stdio.h>
int main() {
char result[10][7] = {
{'1','X','2','X','2','1','1'},
{'X','1','1','2','2','1','1'},
{'X','1','1','2','2','1','1'},
{'1','X','2','X','2','2','2'},
{'1','X','1','X','1','X','2'},
{'1','X','2','X','2','1','1'},
{'1','X','2','2','1','X','1'},
{'1','X','2','X','2','1','X'},
{'1','1','1','X','2','2','1'},
{'1','X','2','X','2','1','1'}
};
// 'total' will be 70 = 10 * 7
int total = sizeof(result);
// 'column' will be 7 = size of first row
int column = sizeof(result[0]);
// 'row' will be 10 = 70 / 7
int row = total / column;
printf("Total fields: %d\n", total);
printf("Number of rows: %d\n", row);
printf("Number of columns: %d\n", column);
}
这个的输出是:
Total of fields: 70
Number of rows: 10
Number of columns: 7
编辑:
正如@AnorZaken 所指出的,将数组作为参数传递给函数并sizeof
在其上打印结果,将输出另一个total
. 这是因为当您将数组作为参数(而不是指向它的指针)传递时,C 会将其作为副本传递,并在两者之间应用一些 C 魔法,因此您传递的方式与您认为的不完全相同。为了确定您在做什么并避免一些额外的 CPU 工作和内存消耗,最好通过引用(使用指针)传递数组和对象。所以你可以使用这样的东西,结果与原始结果相同:
#include <stdio.h>
void foo(char (*result)[10][7])
{
// 'total' will be 70 = 10 * 7
int total = sizeof(*result);
// 'column' will be 7 = size of first row
int column = sizeof((*result)[0]);
// 'row' will be 10 = 70 / 7
int row = total / column;
printf("Total fields: %d\n", total);
printf("Number of rows: %d\n", row);
printf("Number of columns: %d\n", column);
}
int main(void) {
char result[10][7] = {
{'1','X','2','X','2','1','1'},
{'X','1','1','2','2','1','1'},
{'X','1','1','2','2','1','1'},
{'1','X','2','X','2','2','2'},
{'1','X','1','X','1','X','2'},
{'1','X','2','X','2','1','1'},
{'1','X','2','2','1','X','1'},
{'1','X','2','X','2','1','X'},
{'1','1','1','X','2','2','1'},
{'1','X','2','X','2','1','1'}
};
foo(&result);
return 0;
}