gpt4 book ai didi

C - 结构和函数的前向声明

转载 作者:太空狗 更新时间:2023-10-29 15:34:49 25 4
gpt4 key购买 nike

我正在尝试弄清楚前向声明究竟是如何相互作用的。当前向声明一个采用 typedef 结构的函数时,有没有办法让编译器接受以前前向声明(但实际上没有定义)的结构作为参数?

我得到的代码:

typedef struct{
int year;
char make[STR_SIZE];
char model[STR_SIZE];
char color[STR_SIZE];
float engineSize;
}automobileType;

void printCarDeets(automobileType *);

我希望我能做的:

struct automobileType;
void printCarDeets(automobileType *);

//Defining both the struct (with typedef) and the function later

我觉得我要么遗漏了一些非常基本的东西,要么不理解编译器如何处理结构的前向声明。

最佳答案

Typedef 和结构名称位于不同的命名空间中。所以 struct automobileTypeautomobileType 不是一回事。

你需要给你的匿名结构一个标签名才能做到这一点。

.c 文件中的定义:

typedef struct automobileType{
int year;
char make[STR_SIZE];
char model[STR_SIZE];
char color[STR_SIZE];
float engineSize;
}automobileType;

头文件中的声明:

typedef struct automobileType automobileType;
void printCarDeets(automobileType *);

关于C - 结构和函数的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com