我想写一个简单的程序,获取用户列表(列表是一个结构与数据,并指向下一个列表),然后打印它。 我的代码工作正常,但打印后,出现错误“练习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();
}
它对我来说工作得很好。你怎么执行它? – nommyravian 2013-04-10 08:25:44
只有'free'''anchor' =内存泄漏。此外,如果您可以明确声明**哪一行**会为您提供访问违规错误,那将会很好。 – 2013-04-10 08:31:40
printf(“%3d - >”,current_list-> number);给了我这个错误,但它现在似乎正在工作。简单的重启似乎可以解决它。对不起,浪费你的时间。 – 2013-04-10 08:45:47