what does typedef struct node *NODE indicate?

前端 未结 5 1747
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2021-02-20 01:09

    It defines NODE as a synonym for the type struct node *, so when you'll be declaring a variable of type NODE you'll be actually declaring a pointer to struct node.

    Personally, I don't think that such declaration is a good idea: you're "hiding a pointer" (which is almost always a bad idea), and, moreover, you are not highlighting this fact in any way into the new name.

    0 讨论(0)
  • 2021-02-20 01:12

    simply tells you can create pointer of node type using only NODE every time instead of writting struct node * everytime

    0 讨论(0)
  • 2021-02-20 01:12

    what does typedef struct node *NODE indicate?

    IT INDICATES A PERSON WHO HAS NOT LEARNED THAT UPPERCASE IS NO GOOD

    Reserve ALL UPPERCASE identifiers for MACROS.

    Cheers & hth.,

    0 讨论(0)
  • 2021-02-20 01:12

    It makes NODE a typedef for a struct node *.

    0 讨论(0)
提交回复
热议问题