C语言sizeof 和 strlen 的区别

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

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值