各位朋友,每当我写链表代码时,我总会收到此错误
sample.exe中0x57c4e42e(msvcr100d.dll)的未处理异常:0xC0000005:
访问冲突写入位置0x00000000。“
我不知道这个错误是什么,当我输入要添加到链表中的值时会出现此错误
任何人都可以告诉我我做错了什么,它是什么类型的错误,在哪种情况下会出现这样的错误?
这是我的代码,我刚刚编写了两个函数来添加和创建链表。
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.>
typedef struct list
{
int data;
struct list *next;
}list;
list* head=NULL;
list* current=NULL;
list* create(int data)
{
list* ptr=(list*)malloc(sizeof(list));
if(ptr==NULL) exit(0);
ptr->data=data;
if(head==NULL)
{ head=ptr;
current=ptr;
}
else
{ current->next=ptr;
current=ptr;
ptr->next=NULL;
}
return ptr;
}
void add(int data)
{ create(data);
printf("%d added to the list",data);
}
int main()
{
int i=0,choice;
list obj;
while(1)
{
printf("1)create \n1)Add\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Enter value");scanf("%d",i);create(i);break;
case 2:printf("Enter value");scanf("%d",i);add(i);break;
default:exit(0);
}
return 1;
}
}
答案 0 :(得分:1)
head == NULL
时,您无法正确设置新的列表节点。请注意,您的ptr->next
更新缺失了!
最好像这样构建代码:
// Create new node
list* ptr = malloc(sizeof(list));
ptr->data = data;
ptr->next = NULL;
// Link
if (head == NULL)
{
head = ptr;
}
else
{
current->next = ptr;
}
// Update tail
current = ptr;
答案 1 :(得分:-1)
检查一下。我做了类似的事。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}node_list;
void add(node_list *head, int number){
node_list *wsk, *nowy;
wsk = head;
while (wsk->next != NULL)
{
wsk = wsk->next; /* find last element */
}
nowy =(node_list*) malloc (sizeof(node_list));
nowy->data = number;
nowy->next = NULL;
wsk->next = nowy; /* add new element to last element of list */
}
void write_list(node_list *lista)
{
node_list *wsk=lista;
while( wsk != NULL )
{
printf ("data = %d\n", wsk->data);
wsk = wsk->next;
}
}
int main()
{
int i=0;
node_list *first;
first = (node_list*)malloc(sizeof(node_list));
first -> data = NULL;
first -> next = NULL;
add(first, 10);
add(first, 20);
write_list(first);
getchar();
return 1;
}