C语言sizeof 和 strlen 的区别

来源:互联网 发布:catia软件销售怎么样 编辑:程序博客网 时间:2024/04/19 05:20

先来看下面一段简单的代码段

#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