我有 2 个关于我的代码的问题:
- 为什么
struct node *a,*b;
不能在create()
中工作?我收到此消息:b 已使用但未初始化
。它在if
语句中也不起作用。 - 如果我们在普通程序中使用
malloc()
,我们可以像这样使用 free ->free(variablename);
,但是我如何去释放一个单链接名单?
这是我的代码:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int d;
struct node *next;
}*start=NULL;struct node *a,*b;
void create()
{
a=(struct node *)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d",&a->d);
a->next=NULL;
if(start==NULL)
{
start=a;
b=a;
}
else
{
b->next=a;
b=a;
}
}
void display()
{
struct node *a;
printf("\nThe Linked List : ");
a=start;
while(a!=NULL)
{
printf("%d--->",a->d);
a=a->next;
}
printf("NULL\n");
}
void main()
{
char ch;
do
{
create();
printf("Do you want to create another : ");
ch=getche();
}
while(ch!='n');
display();
free(a); // i don't know is this crt?
}
最佳答案
您必须单独释放列表中的每个元素。由 malloc
分配的每个内存片必须用 free
释放。
不要在程序结束时调用 free(a)
,而是调用 freenodes()
。
void freenodes()
{
struct node *a;
a = start;
while(a != NULL)
{
struct node *freenode = a ;
a = a->next;
free(freenode) ;
}
}
关于c - 如何释放我的单链表程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22479645/