gpt4 book ai didi

c - 如何释放我的单链表程序?

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:46 25 4
gpt4 key购买 nike

我有 2 个关于我的代码的问题:

  1. 为什么 struct node *a,*b; 不能在 create() 中工作?我收到此消息:b 已使用但未初始化。它在 if 语句中也不起作用。
  2. 如果我们在普通程序中使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com