What is the purpose of the first “node” in the declaration: “typedef struct node { - - - } Node;”?

前端 未结 6 1329
醉话见心
醉话见心 2020-12-30 08:06

I am studying code examples from my professor in order to become better acquainted with linked data structures.

In our linked-list.c example the professor defines a

6条回答
  •  自闭症患者
    2020-12-30 08:46

    Consider this code:

    #include 
    
    typedef struct {
       int data;
       struct node *next;
    } Node;
    
    int main()
    {
       Node a, b = {10, NULL};
       a.next = &b;
    
       printf("%d\n", a.next->data);
    }
    

    This won't compile. The compiler has no idea what a struct node is, other than it exists. So you might change the definition in the struct to Node *next;. The typedef isn't in scope before it's declared, so it still won't compile. The simple answer is to do as he said, use the node tag after struct, and it works fine.

提交回复
热议问题