【发布时间】:2018-02-17 21:30:58
【问题描述】:
我正在编写一个小程序,它将数据和键存储在链表结构中,并根据用户的键检索数据。该程序还检查它是否是唯一键,如果是唯一键,它会通过在列表的前面创建一个节点来存储数据。但是下面的代码总是抛出分段错误。
#include<stdlib.h>
/* Node having data, unique key, and next */.
struct node
{
int data;
int key;
struct node *next;
}*list='\0',*p;
/* Create a node at the front */
void storeData(int data_x,int key_x)
{
int check_key;
position *nn; //nn specifies newnode
nn=(position)malloc(sizeof(struct node));
/* Segmentation Fault occurs here */
if(list->next==NULL)
{
nn->next=list->next;
nn->data = data_x;
nn->key = key_x;
list->next = nn;
}
else
{
check_key=checkUniqueKey(key_x);
if(check_key != FALSE)
{
printf("The entered key is not unique");
}
else
{
nn->data = data_x;
nn->key = key_x;
nn->next=list->next;
list->next=nn;
}
}
}
/* Retreive data based on a key */
int retreiveData(int key_find)
{
int ret_data = NULL;
p=list->next;
while(p->next != NULL)
{
if(p->key == key_find)
{
ret_data = p->data;
break;
}
p=p->next;
}
return(ret_data);
}
/* Checks whether user key is unique */
int checkUniqueKey(int key_x)
{
int key_check = FALSE;
p=list->next;
while(p->next != NULL)
{
if(p->key == key_x)
{
key_check = TRUE;
break;
}
p=p->next;
}
return(key_check);
}
动态分配后storeData函数出现分段错误。
【问题讨论】:
-
if(list->next==NULL) { nn->next=list->next;您在此处取消引用 NULL 指针。另外:*list='\0'不是指针的正确初始化程序。 -
像这样使用全局变量是非常糟糕的;不要将
'\0'分配给指针,不要将NULL分配给int;代码不完整,但我在任何地方都没有找到你的malloclist,list->next可能因为这个原因而被引用为NULL。 -
@Coder:你为什么回滚我的编辑?
标签: c linked-list singly-linked-list