数组 strlen sizeof

#include <stdio.h>
#include <string.h>


#define _TEST_
#define BUF_SIZE 10


int main(int argc, char *argv[])
{
int i;
char sendBuff[BUF_SIZE];

memset(sendBuff, '0', sizeof(sendBuff));//init 0x30


#ifdef _TEST_  
for(i=0;i<BUF_SIZE*3;i++)
{
if(i%16==0)
printf("\n");
printf("%.2x ",sendBuff[i]);
}
printf("\n");
printf("1-strlen(sendBuff)=%d,sizeof(sendBuff)=%d\n",strlen(sendBuff),sizeof(sendBuff));


memset(sendBuff, 0, sizeof(sendBuff)); //init 0x00
printf("2-strlen(sendBuff)=%d,sizeof(sendBuff)=%d\n",strlen(sendBuff),sizeof(sendBuff));
#endif

return 0;
}

//GCC输出结果

30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 
30 30 30 30 30 30 30 30 30 30 03 00 00 00 
1-strlen(sendBuff)=27,sizeof(sendBuff)=10
2-strlen(sendBuff)=0,sizeof(sendBuff)=10


//结论

先前错误的认为strlen和sizeof的操作会相等,

但是仔细想想是不等的,数组在未被初始化的时候在内存中分配的内存可能是乱码,

而strlen函数返回的是有效字符的长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值