我需要一些帮助来计算二维数组的行和列.好像我不能算列?
#includeint 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'} }; int row = sizeof(result) / sizeof(result[0]); int column = sizeof(result[0])/row; printf("Number of rows: %d\n", row); printf("Number of columns: %d\n", column); }
输出:
行数:10
列数:0
使用数组长度宏更方便(并且更不容易出错):
#include#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0])) int main(void) { char result[10][7]; printf("Number of rows: %d\n", LEN(result)); printf("Number of columns: %d\n", LEN(result[0])); return 0; }
这是整数除法的问题!
int column = sizeof(result[0])/row;
应该
int column = 7 / 10;
在整数除法中7/10==0
.
你想要做的是划分一行的长度,例如.sizeof(result[0])
通过该行的一个元素的大小,例如.sizeof(result[0][0])
:
int column = sizeof(result[0])/sizeof(result[0][0]);
这对我有用(评论解释了原因):
#includeint 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工作和内存消耗,最好通过引用传递数组和对象(使用指针).所以你可以使用这样的东西,结果和原作相同:
#includevoid 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; }