這對我的作品(評論解釋爲什麼):
#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;
}
'INT列=的sizeof(結果[0])/ sizeof(result [0] [0]);' – BLUEPIXY
既然它們是靜態的,那你爲什麼要數它們呢?只需定義行和列大小的常量,而不是使用「幻數」。 – Lundin