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

传入结构体名称作为函数参数打印成员时报struct or union expected错误如何解决

问题根因

  1. C 是静态编译型语言,没有运行时反射能力:代码里的变量名example只在编译阶段有效,编译为二进制程序后变量名会被替换为内存地址,你传入字符串"example"根本无法直接关联到对应的结构体实例,这是所有写法报错的核心原因。
  2. 代码隐含内存错误:结构体的name成员是未初始化的野指针,直接调用strcpy会触发非法内存访问,大概率直接崩溃。

最简修复方案(直接传结构体指针)

这是C语言操作结构体的标准写法,完全满足你的打印需求:

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

typedef struct
{
    int hp;
    // 也可以直接写成char name[20]; 省略手动分配内存的步骤
    char *name;
} bare;

// 函数参数改为结构体常量指针,无需拷贝全量结构体,效率更高
void print_info(const bare *obj);

int main()
{
    bare example;
    example.hp = 5;
    // 给name成员分配足够的内存,多留1位存储字符串结束符'\0'
    example.name = malloc(strlen("John") + 1);
    strcpy(example.name, "John");
    
    // 传入结构体的地址即可
    print_info(&example);
    
    // 释放堆内存避免泄漏
    free(example.name);
    return 0;
}

void print_info(const bare *obj)
{
    // 指针访问结构体成员用->运算符即可
    printf("The hp of %s is %d\n", obj->name, obj->hp);
}

按字符串名匹配结构体的实现方案

如果你确实需要实现最开始的「接收fgets输入的变量名,匹配对应结构体打印」的需求,需要自己手动维护变量名到结构体地址的映射表:

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

typedef struct
{
    int hp;
    char *name;
} bare;

// 定义映射表结构,存储变量名和对应的结构体指针
typedef struct
{
    const char *var_name;
    const bare *obj;
} VarMap;

// 测试用的全局结构体实例
bare example, example2;

void print_info(char *name, const VarMap *map, int map_len);

int main()
{
    // 初始化第一个结构体
    example.hp = 5;
    example.name = malloc(strlen("John") + 1);
    strcpy(example.name, "John");
    // 初始化第二个结构体
    example2.hp = 10;
    example2.name = malloc(strlen("Alice") + 1);
    strcpy(example2.name, "Alice");
    
    // 构建变量名-结构体映射表
    VarMap map[] = {
        {"example", &example},
        {"example2", &example2}
    };
    int map_len = sizeof(map) / sizeof(map[0]);
    
    // 现在可以传入字符串匹配对应的结构体,也可以替换为fgets获取的用户输入
    print_info("example", map, map_len);
    print_info("example2", map, map_len);
    
    free(example.name);
    free(example2.name);
    return 0;
}

void print_info(char *name, const VarMap *map, int map_len)
{
    // 遍历映射表匹配变量名
    for(int i=0; i<map_len; i++){
        if(strcmp(map[i].var_name, name) == 0){
            printf("The hp of %s is %d\n", map[i].obj->name, map[i].obj->hp);
            return;
        }
    }
    printf("未找到名为%s的结构体实例\n", name);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:06:03