what does typedef struct node *NODE indicate?

前端 未结 5 1805
遥遥无期
遥遥无期 2021-02-20 01:00
struct node
{
    int coef;

    int exp;

    struct node *link;
};

typedef struct node *NODE;
5条回答
  •  太阳男子
    2021-02-20 01:06

    NODE becomes an alias for struct node*.


    EDIT: Okay, for the comment (if I write my answer as comment, it would be too long and not formatted):

    There's no different way to write this. Here, typedef is used just to create a synonym/alias for pointer to struct node.
    An example for usage would be:

    void f()
    {
        // some code
        NODE p = NULL;
        // do something with p
        // for example use malloc and so on
        // like: p = malloc( sizeof( struct node ) );
        // and access like: p->coef = ..; p->expr = ..
        // do something with p and free the memory later (if malloc is used)
    }
    

    is the same as

    void f()
    {
        // some code
        struct node* p = NULL;
        // do something with p
    }
    

    Using NODE makes it just shorter (anyway, I wouldn't advise such typedef, as you're hiding, that it's a pointer, not a struct or other type, as mentioned in @Matteo Italia's answer).


    The format, you're referring: "typedef struct{}type_name format" is something else. It's kind of a trick in C, to avoid writing struct keyword (as it's obligatory in C, and NOT in C++). So

    typedef struct node
    {
        //..
    } NODE;
    

    would make NODE alias for struct node. So, the same example as above:

    void f()
    {
        // some code
        NODE p;
        // do something with p
        // note that now p is automatically allocated, it's real struct
        // not a pointer. So you can access its members like:
        // p.coef or p.expr, etc.
    }
    

    is the same as

    void f()
    {
        // some code
        struct node p;
        // do something with p
    }
    

    NOTE that now, p is NOT a pointer, it's struct node.

提交回复
热议问题