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

为何C语言中字符串拼接后sizeof与strlen结果不一致?

为什么sizeof(strp)-1结果为5而strlen(strp)结果为11?

首先看问题里的代码(注意:原代码遗漏了strcat和strlen依赖的头文件):

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

int main(void) {
    char strp[] = "hello";
    char strq[] = " world";
    strcat(strp,strq);
    puts(strp); //hello world
    printf("%d",sizeof(strp)-1);//this gives 5(length of 'hello' -1 for '\0')
    printf("%d",strlen(strp));//gives correct answer(11)
    return 0;
}

核心原因是sizeof和strlen的本质完全不同:

  • sizeof是编译期固定值
    char strp[] = "hello"; 在编译阶段,编译器会根据初始字符串"hello"的长度(5个字符+末尾的'\0'),将strp定义为大小为6的字符数组。sizeof运算符在编译时就确定了该数组的存储空间大小为6,因此sizeof(strp)-1永远是5,和运行时数组内的实际内容无关。

  • strlen是运行时实际字符串长度
    strlen函数的逻辑是从传入的内存地址开始,逐个字符计数,直到遇到第一个'\0'为止(不计入'\0')。虽然这里用strcat拼接字符串的行为已经越界(strp仅有6字节空间,拼接后需要12字节),属于C语言的未定义行为,但碰巧内存中拼接后的字符串末尾存在'\0',所以strlen能数出正确的11。

重要提醒:

代码里的strcat(strp, strq)是错误写法,strp的内存空间不足以容纳拼接后的字符串,越界写入会破坏其他内存区域,可能导致程序崩溃、输出乱码或其他不可预料的问题,这次puts能正常输出只是偶然情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:24:53