c - c中结构内结构的含义
问题描述
有人可以解释我们在做什么时的意思,比如 struct Node* next 做什么。它会创建一个结构类型的指针吗?有关 c 中结构的任何帮助和资源都会有所帮助
struct Node {
int dest;
struct Node* next;
};
解决方案
“结构”本身不是一种类型。“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 的情况。
此外,在实际代码中,您将在遍历链的循环中使用这种结构,而不是像上面那样直接使用。
推荐阅读
- ios - 有没有办法使用 NavigationLink 导航到导航视图内的三个或四个级别?
- java - 尝试为 React Native 项目构建 APK 文件时出错
- qt - 如何获取文件/图像的绝对路径
- c# - 如何获取文本并计算具有相同单词c#的行数?
- python - Seaborn 线图 - 基于峰值的数据
- java - Java内存hsqldb
- python - 剧情怎么掉下来了?(Seaborn,蟒蛇)
- python - 在 python 中,如何让两个文件迭代器以不同的速率迭代行?
- amazon-web-services - AWS VPC 有一个用于出站流量的外部 IP
- tableau-api - 在 tableau 中按类别显示百分比