朋友们,每当我写链表代码时,我总是会收到这个错误
"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)Addn");
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;
}
}
当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;
检查此项。我做了类似的东西。
#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 = %dn", 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;
}