#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;
}
#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函数返回的是有效字符的长度。