#include <stdio.h>
#include <stdlib.h>
#define MAX_ELEMENT 100
typedef struct TreeNode{
int weight;
TreeNode *left_child;
TreeNode *right_child;
} TreeNode;
typedef struct element{
TreeNode *ptree;
int key;
} element;
typedef struct HeapType{
element heap[MAX_ELEMENT];
int heap_size;
} HeapType;
我得到了错误:
error: unknown type name ‘TreeNode’
TreeNode *left_child;
error: unknown type name ‘TreeNode’
TreeNode *right_child;
我不明白为什么...你能解释吗?
答案 0 :(得分:4)
使用您的代码:
typedef struct TreeNode{
int weight;
TreeNode *left_child;
TreeNode *right_child;
} TreeNode;
在解析行TreeNode
之前,名称} TreeNode;
是未知的。处理行TreeNode *left_child;
时,编译器知道存在类型struct TreeNode
,但对类型TreeNode
一无所知。
您还可以使用:
typedef struct TreeNode Treenode;
struct TreeNode
{
int weight;
TreeNode *left_child;
TreeNode *right_child;
};
第一行说“存在一个结构类型struct TreeNode
,而TreeNode
是该类型的别名”。其余代码行定义了struct TreeNode
的含义。
或者,如其他答案所指出的,您可以使用:
typedef struct TreeNode
{
int weight;
struct TreeNode *left_child;
struct TreeNode *right_child;
} TreeNode;
编译器对类型struct TreeNode
足够了解,以便能够在读取定义时处理指向该类型的指针。注释C11 §6.7.2.1 Structure and union specifiers ¶3:
结构或联合不得包含具有不完整或函数类型的成员(因此,结构不得包含其自身的实例,但可以包含指向其自身的实例的指针),……
答案 1 :(得分:3)
您需要写struct TreeNode*
因为编译器仍然不知道TreeNode是什么(没有结构)
答案 2 :(得分:2)
typedef直到结构定义之后才起作用,因此您仍然需要将struct关键字用于指针decls。
typedef struct TreeNode{
int weight;
struct TreeNode *left_child;
struct TreeNode *right_child;
} TreeNode;