c - 双向链表实现显示 C 中的分段错误
问题描述
这是我的 DLL 实现代码片段。
struct node //doubly-linked list
{
int data;
struct node *next; // next-pointer
struct node *prev; // previous-pointer
};
typedef struct node *node;
struct LL //LL has a field 'head' pointing to top of the list
{
node head;
};
typedef struct LL *LL;
node CREATE_NODE(int k)
{
node temp;
temp = (node)malloc( sizeof (node));
if (temp == NULL)
exit(0);
temp->data= k;
temp->next = NULL;
return temp;
}
int main()
{
LL list;
list->head = NULL;//segmentation error
return 0;
}
由于我被要求在问题中使用 typedef 初始化来实现双向链表,有没有其他方法可以初始化头指针以使其为 NULL?
编辑:添加了一些额外的代码来显示插入功能。
void INSERT(LL l, int k) //insert at the front only
{
node y;
y = CREATE_NODE(k); //create an empty list first
y->next = l->head; //next-pointer points to the head
y->prev = NULL;
if (l->head!= NULL)
{
(l->head)->prev = y;
}
l->head = y;
}
解决方案
您的代码存在许多问题。主要的脚射是从这条线上射出的:
typedef struct LL *LL;
现在LL
是指向struct LL
. 将指针隐藏在 atypedef
中被认为是一种非常糟糕的做法,只有可接受的函数指针例外。
因此代码:
LL list;
声明指向 的未初始化指针struct LL
。取消引用此指针会list->head
调用未定义的行为,这可能是由NULL 取消引用和接收SEGFAULT
信号引起的。
我猜目的是:
struct LL list;
list.head = NULL;
推荐阅读
- amazon-web-services - AWS IAM 是否支持允许 AWS 组织内的所有账户的策略?
- c++ - 函数指针 Arduino 作为回调 Bluefruit 库
- java - ANTLR4 查找标记但返回截断的解析树
- c# - 如何将 `|` 操作数应用于字符串?
- php - 许多现有的对 MySQL 与加载表的检查查询并在 php 中进行比较
- javascript - 在请求模块 Javascript 中使用 async/await
- ruby-on-rails - 在 Rails 5 下,使用 helper link_to 和方法 delete 发出 get 和 object#show 而不是 object#destroy
- javascript - 如果语句不能正常工作 [React hooks]
- node.js - 我正在尝试通过 nodejs 访问本地超级账本测试网络链代码,以编写 api
- python - 通过 Excel 制作 CSV 会在第一列名称前显示“”