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

结构体已定义仍提示未定义?C语言结构体使用问题求助

问题分析与解决

你的代码存在两个关键问题:

1. typedef用法错误(可选,但影响类型定义)

你写的typedef struct test1 { ... };没有给结构体类型指定别名。typedef的作用是给已有类型起新名字,正确写法需要在结构体末尾加上别名,例如:

typedef struct test1 {
    int array1[3];
    int array2[3];
} test1;

这样test1就成为该结构体的类型别名,后续可以直接用test1定义变量。如果不用typedef,直接定义结构体即可:

struct test1 {
    int array1[3];
    int array2[3];
};

2. 混淆结构体类型与变量(核心错误)

你直接用test1.array1[1]访问成员完全错误——test1是结构体类型(相当于一个模板),不是具体的变量。必须先创建该类型的变量,才能通过变量访问成员。

修正后的完整代码(使用typedef)

#include <stdio.h>

typedef struct test1 {
    int array1[3];
    int array2[3];
} test1;

int main(void) {
    // 创建结构体变量
    test1 my_test;
    // 通过变量访问成员
    scanf_s(" %d %d", &my_test.array1[1], &my_test.array2[1]);
}

修正后的完整代码(不使用typedef)

#include <stdio.h>

struct test1 {
    int array1[3];
    int array2[3];
};

int main(void) {
    // 创建结构体变量
    struct test1 my_test;
    // 通过变量访问成员
    scanf_s(" %d %d", &my_test.array1[1], &my_test.array2[1]);
}

你提到“单独创建变量则无问题”,是因为单独创建变量才是符合C语言语法的正确用法——只有具体的变量才会占用内存,能存储数据并访问成员,类型本身只是一个定义模板,不能直接使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:50:41