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

C语言中结构体变量在main函数中无法正常生效的问题

C语言跨文件修改结构体变量无输出的问题解决

问题根源

  1. 值传递导致修改无效:你当前的this_test函数采用值传递,函数内的t是主函数结构体的副本,修改副本的string成员不会影响主函数里的原结构体。
  2. 未初始化的野指针:主函数中struct tst t;定义的结构体,string成员是未初始化的野指针,直接打印会触发未定义行为,自然不会有有效输出。

修复方案

方案1:传递结构体指针(推荐)

通过指针直接操作原结构体的内存,这是C语言中修改外部变量的常用方式。

修改头文件tesst.h的函数声明:

#ifndef _TESST_H
#define _TESST_H

struct tst
{
   char *string;
};

// 将参数改为结构体指针
void this_test(struct tst *t);

#endif

修改实现文件的函数逻辑:

#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"

void this_test(struct tst *t)
{
   // 使用->访问指针指向的结构体成员
   t->string = "this is test";
}

修改主函数的调用方式:

#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"

int main()
{
   struct tst t;
   // 传递结构体的地址给函数
   this_test(&t);
   printf("%s\n", t.string); // 加换行符让输出更易读

   return 0;
}

方案2:返回修改后的结构体

如果不想使用指针,可以让函数返回修改后的结构体,主函数接收返回值更新原变量。

修改头文件tesst.h的函数声明:

#ifndef _TESST_H
#define _TESST_H

struct tst
{
   char *string;
};

// 函数返回结构体类型
struct tst this_test(struct tst t);

#endif

修改实现文件的函数逻辑:

#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"

struct tst this_test(struct tst t)
{
   t.string = "this is test";
   return t;
}

修改主函数的调用逻辑:

#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"

int main()
{
   struct tst t;
   // 接收函数返回的修改后的结构体
   t = this_test(t);
   printf("%s\n", t.string);

   return 0;
}

方案对比

  • 方案1(指针传递)更高效,不需要拷贝整个结构体,适合结构体较大的场景。
  • 方案2(返回结构体)代码更直观,但会产生结构体拷贝,小结构体使用更合适。

内容的提问来源于stack exchange,提问作者Hakkı Anıl Ragıboğlu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:00:56