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

C语言如何将struct结构体的多个char成员拼接为空格分隔的字符串并排查无输出问题

问题原因
  • 核心原因是printf输出内容未携带换行符\n:常规环境下标准输出流stdout默认是行缓冲模式,只有遇到换行符、缓冲区被填满、或者主动调用fflush(stdout)时才会将缓冲区内容打印到终端。你的两次printf调用都没有加换行符,程序退出时缓冲区内容还没来得及刷新,自然看不到输出。
  • 潜在风险:当前你用sprintf直接写入长度固定的box数组,后续如果结构体成员字符串变长,很容易出现缓冲区溢出,触发未定义行为。
修复实现

你拼接字符串的逻辑本身是正确的,只要调整输出逻辑、补充安全校验即可,修改后的代码如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct donor
{
    char *name;
    char *code ;
    char *donor;
    char *ship;
    char *quant;
    char *id;
    char *string;
    struct donor *link;
};

typedef struct donor Donor;
char box[20];
int main(){
    Donor *node = malloc(sizeof(Donor));
    // 校验内存分配结果
    if (node == NULL) {
        perror("malloc failed");
        return 1;
    }
    node->id = strdup("GA");
    node->code = strdup("HI");
    node->donor = strdup("TO");
    node->ship = strdup("GD");
    node->quant = strdup("UT");
    // 简单校验strdup分配结果
    if (!node->id || !node->code || !node->donor || !node->ship || !node->quant) {
        perror("strdup failed");
        return 1;
    }

    // 改用snprintf避免缓冲区溢出
    snprintf(box, sizeof(box), "%s %s %s %s %s", node->id, node->code, node->donor, node->ship, node->quant);
    // 输出加换行触发缓冲刷新
    printf("%s\n", box);
    node->string = strdup(box);
    if (node->string) {
        printf("%s\n", node->string);
    }

    // 释放所有动态分配的内存,避免内存泄漏
    free(node->id);
    free(node->code);
    free(node->donor);
    free(node->ship);
    free(node->quant);
    free(node->string);
    free(node);
    return 0;
}

修改后运行即可看到两次输出GA HI TO GD UT,node->string也能正常存储你需要的空格分隔字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:54:08