数组的sizeof

数组的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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值