简体   繁体   中英

typedef struct and pointer

When we have:

      struct node{.....}
      typedef struct node Node;
      typedef Node *ptr;

is ptr a pointer to struct node or typedef changes the meaning of it?

The definition

typedef struct node *ptr;

will make ptr an alias for struct node * .

Afterwards you can do either

struct node *some_pointer;

Or

ptr some_pointer;

Both will define the variable some_pointer to be a pointer to the node structure.

But making type-aliases of pointer types is not something I recommend. It can make the code harder to read, understand and maintain.

Take for example the most common problem that I've seen here on Stack Overflow when it comes to pointer type aliases:

ptr some_pointer = malloc(sizeof(ptr));

That allocates memory enough for a pointer to the structure, not for the whole structure. If using eg

Node *some_pointer = malloc(sizeof(Node*));

that error would be much clearer and easier to find.

See Is it a good idea to typedef pointers?

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