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

C语言嵌套结构体字符串存储异常:打印结果拼接的原因排查

结构体字符串输出异常问题分析

先看你的代码定义:

struct Phone{
    char description[4];
    char number[10];
};

struct Patient{
    int id;
    char name[15];
    struct Phone phone;
};

struct Patient patient = {
    1024, "Shaggy Yanson", {"CELL","3048005191"} 
};

问题原因

完全是结构体定义导致的:

  • C语言的字符串必须以'\0'作为结束标记,"CELL"是4个字符,你给description定义的长度刚好是4,只能放下这4个字符,没有多余空间存储结束符'\0'。
  • 结构体里description和number是连续内存存储的,当用printf("%s", patient.phone.description)打印时,因为找不到结束符,程序会一直往后读取内存,把后面number数组的内容也一并输出,所以结果变成了CELL3048005191。

临时解决方法(因你无法修改数组)

打印时手动限制输出长度,避免越界读取:

// 只打印前4个字符,无需依赖字符串结束符
printf("%.4s\n", patient.phone.description);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:05:26