简体   繁体   English

为什么递归 typedef 允许指针不匹配?

[英]Why is a pointer mismatch allowed for a recursive typedef?

I've been learning C on learn-c.org我一直在 learn-c.org 上学习 C

After covering the unit regarding typedef declarations and structs.在介绍了有关 typedef 声明和结构的单元之后。 They finished with what they called "a recursive definition of a linked list" I found fairly straightforward, except for what seems like a mismatched pointer....他们完成了他们所谓的“链表的递归定义”,我发现它相当简单,除了看起来像不匹配的指针......

typedef struct node{
    int val;
    struct node* next;
}node_t

// usage

node_t* head = NULL;
head = (node_t*) malloc(sizeof(node_t));
head->val = 1;
head->next = (node_t*) malloc(sizeof(node_t));
head->next->val = 2;
head->next->next = (node_t*) malloc(sizeof(node_t));
head->next->next->val = 3;

My understanding is, by supplying typedef struct node , we are able to declare the node pointer next within the structure.我的理解是,通过提供typedef struct node ,我们可以在结构中声明next节点指针。

My confusion occurs on line 11. We are dynamically allocating memory for our next node, but we cast the void pointer as a node_t pointer, not a node pointer -- despite that fact that head->next is a (node*) type.我的困惑发生在第 11 行。我们为下一个节点动态分配 memory,但我们将 void 指针转换为node_t指针,而不是node指针——尽管head->next(node*)类型。 Why is this allowed?为什么允许这样做? Is C simply just recasting to a (node*) behind the scenes, and (node_t*) is used for readability? C 是否只是在幕后重铸为(node*) ,而(node_t*)用于提高可读性?

The typedef makes node_t equivalent to struct node , so anywhere you might use struct node you can use the shorter node_t instead. typedef使node_t等效于struct node ,因此在任何可能使用struct node的地方都可以使用较短的node_t So (node_t*) is equivalent to (struct node*) .所以(node_t*)等价于(struct node*)

The one exception is inside the structure declaration itself, because the name being defined isn't usable until after the typedef statement (just as you can't use a function or variable before they're declared).一个例外是在结构声明本身内部,因为要定义的名称在typedef语句之后才能使用(就像在声明它们之前不能使用 function 或变量一样)。

BTW, it's not necessary to cast the result of malloc() .顺便说一句,没有必要强制转换malloc()的结果。 It returns void* , and C allows this to be assigned to any pointer type without an explicit cast.它返回void* ,并且 C 允许将其分配给任何指针类型,而无需显式强制转换。 See Do I cast the result of malloc?请参阅是否要转换 malloc 的结果?

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

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