With your code:
typedef struct TreeNode{
int weight;
TreeNode *left_child;
TreeNode *right_child;
} TreeNode;
the name TreeNode
is not known until the line } TreeNode;
is parsed. When processing the line TreeNode *left_child;
, the compiler knows that there is a type struct TreeNode
, but it doesn't know anything about a type TreeNode
.
You can also use:
typedef struct TreeNode Treenode;
struct TreeNode
{
int weight;
TreeNode *left_child;
TreeNode *right_child;
};
The first line says "there is a a structure type struct TreeNode
, and TreeNode
is an alias for that type". The remaining lines of code define what it means to be a struct TreeNode
.
Alternatively, as the other answers point out, you can use:
typedef struct TreeNode
{
int weight;
struct TreeNode *left_child;
struct TreeNode *right_child;
} TreeNode;
The compiler knows enough about the type struct TreeNode
to be able to handle pointers to the type as it reads the definition. Note C11 §6.7.2.1 Structure and union specifiers ¶3:
A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), …