我正在尝试编写一个简单的程序,从用户那里获取一个列表(一个列表是一个带有数据的结构,以及一个指向下一个列表的指针),然后打印它。我的代码工作正常,但打印后出现错误“练习 4.exe 中 0x011e1502 处的未处理异常:0xC0000005:访问冲突读取位置 0xcdcdcdcd。”
谁能告诉我为什么?这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef int list_data;
typedef struct list
{
list_data number;
struct list* next_list;
} list; //definition of a list
list* create_list()
{
list* anchor;
anchor=(list*)malloc(sizeof(list));
anchor->next_list=NULL;
return anchor; // allocates a memory for a list and returns address of first block
}
list* insert_list(list* current_position,list_data x)
{
list* temp;
temp=(list*)malloc(sizeof(list));
temp->number=x;
temp->next_list=current_position->next_list;
current_position->next_list=temp;
return temp; //inserts a new block with a data of x
}
void printlist(list* anchor)
{
list* current_list=anchor->next_list;
while(current_list!=NULL)
{
printf("%3d -> ",current_list->number);
current_list=current_list->next_list;
}
printf("End\n");
}
void scan_list(list* anchor)
{
int num1=1;
list* current_position=anchor;
printf("Enter values until 0\n");
while(num1!=0)
{
scanf("%d",&num1);
if(num1)
current_position=insert_list(current_position,num1);
}
}
void main()
{
list* anchor;
anchor=create_list();
scan_list(anchor);
printf("\n");
printlist(anchor);
free(anchor);
getch();
}