And*_*ant 174
显然,Cell不能包含另一个单元格,因为它变成永无止境的递归.
但是,Cell CAN包含指向另一个单元的指针.
typedef struct Cell {
bool isParent;
struct Cell* child;
} Cell;
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 26
在C中,您无法使用结构本身引用您正在创建的typedef.您必须使用结构名称,如以下测试程序中所示:
#include <stdio.h>
#include <stdlib.h>
typedef struct Cell {
int cellSeq;
struct Cell* next; /* 'tCell *next' will not work here */
} tCell;
int main(void) {
int i;
tCell *curr;
tCell *first;
tCell *last;
/* Construct linked list, 100 down to 80. */
first = malloc (sizeof (tCell));
last = first;
first->cellSeq = 100;
first->next = NULL;
for (i = 0; i < 20; i++) {
curr = malloc (sizeof (tCell));
curr->cellSeq = last->cellSeq - 1;
curr->next = NULL;
last->next = curr;
last = curr;
}
/* Walk the list, printing sequence numbers. */
curr = first;
while (curr != NULL) {
printf ("Sequence = %d\n", curr->cellSeq);
curr = curr->next;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
虽然它可能比标准中的这个要复杂得多,但你可以把它想象成编译器struct Cell在第一行typedef知道但不知道tCell直到最后一行:-)这就是我记得那个规则的方法.
小智 12
有一种解决方法:
struct Cell {
bool isParent;
struct Cell* child;
};
struct Cell;
typedef struct Cell Cell;
Run Code Online (Sandbox Code Playgroud)
如果你这样声明,它会正确告诉编译器struct cell和plain-ol'-cell是相同的.所以你可以像平常一样使用Cell.尽管如此,仍然必须在初始声明本身内使用struct Cell.
我知道这篇文章很老,但为了获得你想要的效果,你可能想尝试以下方法:
#define TAKE_ADVANTAGE
/* Forward declaration of "struct Cell" as type Cell. */
typedef struct Cell Cell;
#ifdef TAKE_ADVANTAGE
/*
Define Cell structure taking advantage of forward declaration.
*/
struct Cell
{
int isParent;
Cell *child;
};
#else
/*
Or...you could define it as other posters have mentioned without taking
advantage of the forward declaration.
*/
struct Cell
{
int isParent;
struct Cell *child;
};
#endif
/*
Some code here...
*/
/* Use the Cell type. */
Cell newCell;
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中提到的两种情况中的任何一种情况下,您必须将您的子Cell结构声明为指针.如果你不这样做,那么你将得到"字段'子'具有不完整类型"错误.原因是必须定义"struct Cell",以便编译器知道在使用它时要分配多少空间.
如果您尝试在"struct Cell"的定义中使用"struct Cell",那么编译器还不能知道"struct Cell"应该占用多少空间.但是,编译器已经知道指针占用了多少空间,并且(使用前向声明)它知道"Cell"是一种"struct Cell"(尽管它还不知道"struct Cell"有多大) ).因此,编译器可以在正在定义的结构中定义"Cell*".
小智 5
另一种方便的方法是使用,structure 标记对结构进行预定义:
//declare new type 'Node', as same as struct tag
typedef struct Node Node;
//struct with structure tag 'Node'
struct Node
{
int data;
//pointer to structure with custom type as same as struct tag
Node *nextNode;
};
//another pointer of custom type 'Node', same as struct tag
Node *node;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101054 次 |
| 最近记录: |