sizeof是求数据类型所占的空间大小,而strlen是求字符串的长度,区别还是挺大的
下面直接来看代码:
#include #include int main()
{
char a[]="hello";
char *b="hello";
char c[100]="hello";
char d[]={'h','e','l','l','o'};
char e[]={'h','e','\0','l','l','0'};
printf("a:sizeof:%d strlen:%d\n",sizeof(a),strlen(a));
printf("b:sizeof:%d strlen:%d\n",sizeof(b),strlen(b));
printf("c:sizeof:%d strlen:%d\n",sizeof(c),strlen(c));
printf("d:sizeof:%d strlen:%d\n",sizeof(d),strlen(d));
printf("e:sizeof:%d strlen:%d\n",sizeof(e),strlen(e));
return 0;
}
几个典型的例子我应该都举出来了
接着是运行截图:
我们分行略微解释下:
a:sizeof算上结束符'\0',strlen没算上
b:64位机上不管什么char*、int*都是8位的,32位机4位
c:sizeof求空间,给100个就是100个空间,不过加上'\0'你只能写99个字符
d:这个字符的都一样
e:sizeof算上'\0',strlen遇上'\0'结束
看懂上述strlen与sizeof的区别,以后看程序也差不多够用了