问题描述
我怎么能在这个结构的定义指针指向下一个结构:
How can I have a pointer to the next struct in the definition of this struct:
typedef struct A {
int a;
int b;
A* next;
} A;
这是我第一次写的,但它不能正常工作。
this is how I first wrote it but it does not work.
推荐答案
您可以定义的typedef和远期首先声明结构在一个说明书,然后在随后的定义中定义的结构。
You can define the typedef and forward declare the struct first in one statment, and then define the struct in a subsequent definition.
typedef struct A A;
struct A
{
int a;
int b;
A* next;
};
编辑:正如其他人所说,如果没有向前declaratation的结构名称仍然是结构定义(即你可以使用结构A
)内有效,但类型定义为不可用,直到typedef的定义完成后(因此使用刚 A
不会是有效)。这可能不是太大的关系只用一个指针成员,但如果你有很多的自我型指针的复杂数据结构,可能不太易于使用的。
As others have mentioned, without the forward declaratation the struct name is still valid inside the struct definition (i.e. you can used struct A
), but the typedef is not available until after the typedef definition is complete (so using just A
wouldn't be valid). This may not matter too much with just one pointer member, but if you have a complex data structure with lots of self-type pointers, may be less wieldy.
这篇关于C:指针在结构定义结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!