简体   繁体   English

typedef结构体和指针

[英]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? ptr是指向struct节点或typedef的指针会改变它的含义吗?

The definition 定义

typedef struct node *ptr;

will make ptr an alias for struct node * . ptr作为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. 两者都将变量some_pointer定义为指向node结构的指针。

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? 请参见使用typedef指针是一个好主意吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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