You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中NULL终止字符串长度为何低于预期?代码实例答疑

为什么这段C代码的strlen输出是0而非预期的2?

先看问题中的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char *str = calloc(3, sizeof(char));
  str[2] = '\0';
  
  printf("%ld", strlen(str));

  free(str);
}

你的猜测完全正确:

  • calloc函数的特性是分配内存后自动将所有字节初始化为0,而ASCII码里的0对应的就是字符串结束符'\0'。所以用calloc(3, sizeof(char))得到的3个字符位置,str[0]、str[1]、str[2]一开始就都是'\0',后续给str[2]赋值'\0'属于重复操作,没有实际作用。
  • strlen的工作逻辑是从传入的指针位置开始逐个字节扫描,直到遇到第一个'\0'就停止,统计的是这个结束符之前的非结束符字符数量。这里str[0]就是'\0',所以strlen直接返回0,不会继续往后检查str[1]和str[2]。

如果想要得到预期的输出2,需要给str[0]和str[1]设置非'\0'的字符,示例代码如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char *str = calloc(3, sizeof(char));
  str[0] = 'a';
  str[1] = 'b';
  // str[2] 已被calloc初始化为'\0',无需重复赋值
  printf("%ld", strlen(str)); // 此时输出2

  free(str);
}

内容的提问来源于stack exchange,提问作者bleschunov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:52:19