数组的sizeof值等于数组所占用的内存字节数,如:
char a1 = "abc";
int a2[3];
sizeof(a1);// 结果为4,字符末尾还存在一个NULL终止符
sizeof(a2);// 结果为3*4=12,依赖于int;
//求数组元素的个数
int count1 = sizeof(a1)/sizeof(char); // 总长度/单个元素的长度,char型
int count2 = sizeof(a2)/sizeof(a2[0]); // 总长度/第一个元素的长度 int型
int array1[3][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11,12, 13, 14, 15}};
int totalByte1 = sizeof(array1); // 3 * 5 * 4(int类型)
int totalSize1 = sizeof(array1)/sizeof(int); // (3 * 5 * 4 / 4)
int totalRowByte1 = sizeof(array1[0]); // 5 * 4(int类型)
int totalRow1 = sizeof(array1)/sizeof(array1[0]); // 有3行
int totalCol1 = sizeof(array1[0])/sizeof(int); // 一行有5列
printf("totalByte1: %d, totalSize1: %d, totalRowByte1: %d, totalRow1: %d, totalCol1: %d", totalByte1, totalSize1, totalRowByte1, totalRow1, totalCol1);
//打印结果:totalByte1: 60, totalSize1: 15, totalRowByte1: 20, totalRow1: 3, totalCol1: 5
int array1[3][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11,12, 13, 14, 15}};
int array2[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11,12}, {13, 14, 15, 16}};
int r1 = sizeof(array1)/sizeof(array1[0]); // 3行
int r2 = sizeof(array2)/sizeof(array2[0]); // 4行
int c1 = sizeof(array1[0])/sizeof(array1[0][0]); // 5列
int c2 = sizeof(array2[0])/sizeof(array2[0][0]); // 4 列
printf("r1: %d, r2: %d, c1: %d, c2: %d", r1, r2, c1, c2);
//打印结果 r1: 3, r2: 4, c1: 5, c2: 4