strlen是函数,而sizeof是算符。strlen需要进行一次函数调用,而对于sizeof而言,因为缓冲区已经用已知字符串进行了初始化,起长度是固定的,所以sizeof在编译时计算缓冲区的长度。
因为sizeof()测试的是数组的长度。而strlen测试的是字符串的长度。在定义数组时,字符串后面还有一个结束标志'\0',这个也要算进去!
- #include <stdio.h>
- #include <string.h>
- main()
- {
- char ss[]="string";
- printf("%d %d \n",sizeof(ss),strlen(ss));
- }
#include <stdio.h>
#include <string.h>
main()
{
char ss[]="string";
printf("%d %d \n",sizeof(ss),strlen(ss));
}
代码修改下:
- #include <stdio.h>
- #include <string.h>
- main()
- {
- char ss[]="string";
- ss[0]=0;
- ss[1]='\0';
- ss[2]='0';
- printf("%d %d \n",sizeof(ss),strlen(ss));
- }
#include <stdio.h>
#include <string.h>
main()
{
char ss[]="string";
ss[0]=0;
ss[1]='\0';
ss[2]='0';
printf("%d %d \n",sizeof(ss),strlen(ss));
}
声明x的时候x里面存储的是"string\0",最后的\0是结束符,所以sizeof(x)就是7。 而\0的asccii码值为0,strlen(x)是计算到\0位置,strlen(x)也就是0了。