先来看下面一段简单的代码段
#include <stdio.h>
int main(int argc, const char * argv[]) {
const char str[] = "hello";
printf("%lu %d\n",sizeof(str), strlen(str));
return 0;
}
输出 6 5
我们知道, C 字符串会在末尾添加一个 \0 作为终止符,
strlen() 是函数,其结果在运行时才能知道。获得 C 字符串的大小, 不包括 \0 本身
sizeof() 是运算符,其结果在编译时就确定好了,返回的是所占空间的大小
char mystr[100] = "test";
printf("%lu\n",sizeof(mystr)); // 输出100
printf("%u\n", (unsigned)strlen(mystr)); // 输出4
char str[] = "hello"; // 4个字符, 该声明在编译时可确定
strcpy(str, "hello world"); // 11个字符
printf("%lu\n", sizeof(str)); // 输出 6,sizeof()是运算符,其值在编译时就确定好了
printf("%u\n", strlen(str)); // 输出 11, strlen()是函数,其值在运行时才确定
参考
https://stackoverflow.com/questions/9937181/sizeof-vs-strlen
http://zh.cppreference.com/w/c/string/byte/strlen
本文深入探讨了C语言中字符串处理的两种关键函数:sizeof() 和 strlen() 的使用区别。通过具体示例说明了如何获取字符串的长度及所占内存大小,并解释了两者之间的差异。
1185

被折叠的 条评论
为什么被折叠?



