简体   繁体   中英

what does typedef struct node *NODE indicate?

struct node
{
    int coef;

    int exp;

    struct node *link;
};

typedef struct node *NODE;

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.

它使NODE成为struct node *的 typedef。

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 .

只是告诉你可以每次只使用 NODE 创建节点类型的指针,而不是每次都写 struct node *

what does typedef struct node *NODE indicate?

UPPERCASE IS NO GOOD

Reserve ALL UPPERCASE identifiers for MACROS .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM