gpt4 book ai didi

c - main() 之前的结构体原型(prototype)

转载 作者:行者123 更新时间:2023-12-02 06:18:11 24 4
gpt4 key购买 nike

拥有 struct -
typedef struct Point{
....
}

我想写它的prototypemain() 之前, 就像是 -

typedef struct Point  ;

int main() {
Point p1 ,p2 ;
...
}

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

以上给了我错误 - unknown type name 'Point' .

我怎么能做到这一点?

编辑:

我知道如果我定义为 struct 会起作用在 main() 之前.我只想知道有没有 prototye类似于 function prototye .

最佳答案

您不能这样做,因为 C 语言是围绕一次编译进行组织的。在使用类型名称来声明或定义某些内容时,该类型已被先前声明过。

这条规则有一个放宽,即:您可以在 C 中定义不完整类型。但是,不完整类型不能用于定义对象:至少,不能用于定义某些类型的对象。所以这是无效的:

struct foo;  /* introduces incomplete type foo */

struct foo x; /* incomplete type for external definition is okay, as long
as the type is completed before the end of the translation unit. */

extern struct foo e; /* incomplete type for external declaration is allowed even if
the type is not completely known in this translation unit
at all. A definition of the object e must exist somewhere
in the linked program---unless e is not used; then a definition
need not exist at all. */

void func(void)
{
struct foo y; /* incomplete type not okay here */
}

struct bar {
struct foo z; /* not okay here */
};

struct foo {
char *s;
}; /* struct foo is now a complete type, but it's too late in the file */

上面的最后一个声明,完成了类型 struct foo允许 struct foo x;定义有效。所以在 C 类型系统中有一些“词法追溯”的 Action ;它只是不一般。

标记为“不好”的情况要求结构类型在源代码中的该点是完整的。

如果要定义 Point 类型的局部变量在您的 main函数,该类型必须在该函数之前声明并完成。如果该类型不完整,您仍然可以定义 Point * 类型的变量。 : 指向 Point 的指针.但是这些指针不能被取消引用。

关于c - main() 之前的结构体原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20363831/

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