c - 在没有虚拟节点的链表前面插入
问题描述
我正在尝试插入按节点-> 名称排序的链表的前面,并且我在文件系统-> curr-> subdir 中没有虚拟节点
typedef struct Unix{
struct Node *curr;
struct Node *root;
}Unix;
typedef struct Node{
struct Node *next;
struct Node *subdir;
struct Node *parent;
char *name;
char *field;
}Node;
下面是我插入按名称排序的链表
/* iter is a node used to traverse LL */
if(iter-> next == NULL && strcmp(iter->name, arg) > 0){
if(iter == filesystem-> curr-> subdir){
/* error occurs when placing node in the front of the list */
temp = malloc(sizeof(Node));
temp-> parent = filesystem-> curr-> subdir-> parent;
temp-> subdir = NULL;
temp-> name = malloc(strlen(filesystem->curr->subdir->name) + 1);
strcpy(temp-> name, filesystem-> curr-> subdir-> name);
temp-> next = NULL;
/* add is the node that's being inserted */
add-> next = temp;
filesystem-> curr->subdir = add;
尝试将 add 作为 filesystem-> curr-> subdir 中的第一个节点并将前一个 subdir 节点移动到 add-> next 时发生错误。
编辑:该程序是unix机器的基本模拟。
解决方案
这就是我开始怀疑错误的地方(就在代码的开头):
add-> parent = malloc(sizeof(Node));
add-> parent = filesystem-> curr;
你分配add-> parent
了两次,这意味着它显然会获得后一个任务,而前一个任务“浪费了”。
除了程序中的内存泄漏(因为您将无法释放此分配的内存块)之外,设置add-> parent
为该值很可能不是您的想法。
推荐阅读
- javascript - 隐藏错误直到用户离开输入
- javascript - 如何从 React Img 组件中获取值
- javascript - 如何在javascript中添加两个数字并在标题中显示结果
- git - 如何将存储库添加到另一个,作为 GitHub 上的文件夹
- python - python:打开文件时出现“TypeError:预期的str,字节或os.PathLike对象,而不是列表”
- swift - 使用 XIB 将数据从 UIViewController 传递到自定义 UIView
- google-calendar-api - 使用 Google Calendar API 检索域中的所有事件
- asp.net-mvc - 找不到源 - 找不到 RouteProvider
- ggplot2 - 在 R 中可视化线性混合模型
- java - 将包含数字的字符串与包含相同的另一个字符串相乘?