c中的类型声明和声明结构

type declaration and declaring struct in c

我在名为 vector.h

的头文件中有以下内容
typedef struct coordinates coordinates;

坐标结构应该有两个变量。 xy

如何在不更改头文件中的任何内容的情况下包含这两个变量 xy

我的想法是在main.c

中写下以下内容
coordinates{
int x;
int y;
};

我写上面是因为我已经在vector.h中写了一个typedef struct coordinates。所以,如果我再写一次,它就会重复。但是上面的语法本身是错误的,因为编译器会抛出错误。如果我理解错误的结构或帮助我如何在结构中声明变量,请帮助我。

我假设你的意思是

typedef struct coordinates
{
    int x;
    int y;
} coordinates;

然后只需使用以下行创建一个结构

coordinates c;
c.x = 0;
c.y = 1;

此声明在 header

typedef struct coordinates coordinates;

不是很有用,因为在大多数情况下通常需要完整的结构定义。所以一般来说,最好在 header 后附加完整的结构定义。

例如

typedef struct coordinates coordinates;
struct coordinates
{
    int x;
    int y;
};

仅在不需要结构的竞争类型的情况下,单个 typedef 声明就足够了。例如,当仅声明指向结构的 objects 的指针时。

如果您不能更改 header,则包含此定义

struct coordinates
{
    int x;
    int y;
};

在引用结构的模块中。

I have the following in the header file named vector.h

typedef struct coordinates coordinates;

这是将标识符 coordinates 声明为类型 struct coordinates 的别名,就该声明而言,它本身就是一个 "incomplete type"。

How can I include these two variables x and y without changing anything in header file?

struct coordinates需要"completed"定义才能访问成员:

struct coordinates {
    int x;
    int y;
};

无论您通过类型名称 struct coordinates 还是通过其别名 coordinates 访问该类型实例的成员,此类定义都需要在范围内。通常将这样的定义放在头文件中,以便在翻译单元之间适当共享,但是如果您只需要访问一个文件中的成员(或结构的整体大小),那么您可以改为上面的类型定义仅在该文件中。或者,您可以在每个想要访问成员的翻译单元中复制相同的定义,但这种形式很差且难以维护。

typedef struct coordinates coordinates;

是不完整的声明,因此当您尝试在 main.c 文件中声明结构的成员时,编译器将抛出错误。

coordinates{
int x;
int y; 
};

抛出的错误将是预期的标识符。编译器正在寻找声明,但无法找到。

您可以在 main.c

中像这样声明坐标结构
typedef struct coordinates{
    int x;
    int y;
}coordinates;

然后你就可以将它用作类型了。 我不建议这样做,因为这是一个重复的练习,而不是一个好的编程习惯。

最好的方法是像这样在 vector.h 文件中声明结构:

typedef struct coordinates{
    int x;
    int y;
}coordinates;

然后在您的 main.c 文件中使用它

希望对您有所帮助!