首页 > 解决方案 > c中结构内结构的含义

问题描述

有人可以解释我们在做什么时的意思,比如 struct Node* next 做什么。它会创建一个结构类型的指针吗?有关 c 中结构的任何帮助和资源都会有所帮助

struct Node {
    int dest;
    struct Node* next;
};

标签: cstructgraph

解决方案


“结构”本身不是一种类型。“struct [tag]”是一种类型,例如代码中的“struct Node”。

在您的情况下,您定义了一个结构类型。该类型的每个结构都将包含一个指向该类型的另一个结构的指针,作为称为“next”的成员。

这允许您在所谓的链表中将结构链接在一起。您将指向第一个结构的指针存储在变量中,然后您可以沿着链接链向下找到您需要的结构。

例如,你可以做

struct Node *start;
start = malloc(sizeof struct Node);
start->dest = 7;
start->next = malloc(sizeof struct Node);
start->next->dest = 13;
start->next->next = malloc(sizeof struct Node);
start->next->next->dest = 19;
printf("%d %d %d\n", start->dest, start->next->dest, start->next->next->dest);
free(start->next->next);
free(start->next);
free(start);

请注意,此代码省略了所有错误处理,在实际代码中,您必须处理 malloc 返回 NULL 的情况。

此外,在实际代码中,您将在遍历链的循环中使用这种结构,而不是像上面那样直接使用。


推荐阅读