的typedef stuct在C向前声明 [英] typedef stuct with forward declaration in C

查看:142
本文介绍了的typedef stuct在C向前声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的:

typedef struct Data DATA, *DATA_PTR;
typedef struct Units UNITS, *UNITS_PTR;

struct Data
{
    double miscData;
    UNITS units;
};

struct Units
{
    double x[2];
    double y[2];
    double z[2];
};

在我的 project_typedef.h 文件。

在另一个文件中,我有这样的:

In another file, I have something like:

void fileInput(DATA_PTR data)
{
     //usual declarations and other things
     data->miscData = 0; //Works!
     data->units.x[0] = 5; //Doesn't work
     //etc...
}

但是,这并不工作,因为单位在 project_typedef.h 数据宣布后(如果我切换它的工作顺序)。我得到的错误是左.X必须有结构/联合。我以为向前声明将解决这个问题。为什么不呢?

However, this doesn't work since units is declared after data in project_typedef.h (if I switch the order it works). The error that i get is "left of '.x' must have struct/union type". I thought that the forward declaration would fix this issue. Why not?

推荐答案

定义数据,所有成员都必须是完整的类型。由于单元是不是在这一点上一个完整的类型,这是行不通的。 (相比之下, UNITS_PTR 将会的罚款,因为指向不完全类型齐全的类型。)

When you define Data, all members must be complete types. Since UNITS isn't a complete type at that point, this doesn't work. (By contrast, UNITS_PTR would be fine, since pointers to incomplete types are complete types.)

简而言之上面的数据定义中的单位定义,你应该罚款。

Simply put the Units definition above the Data definition and you should be fine.

(正如@cnicutar已经指出的那样,你还用数组 X 错误的。)

(As @cnicutar already noted, you're also using the array x wrong.)

这篇关于的typedef stuct在C向前声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆