永发信息网

1.为什么我用free()老是报错 2 我想要在位序一前插入数据时,输出老是有-84215045

答案:1  悬赏:30  手机版
解决时间 2021-11-29 17:16
  • 提问者网友:蔚蓝的太阳
  • 2021-11-29 00:05
1.为什么我用free()老是报错 2 我想要在位序一前插入数据时,输出老是有-84215045
最佳答案
  • 五星知识达人网友:冷風如刀
  • 2021-11-29 00:38
free报错是因为你创建了过后应该到程序最后进行释放,假设你在创建过后就释放,他就不存在了,你就不能再访问他了,当然你输出就出错了
--------
输出-84215045,是你定义了一个表头结点,跳过他,不要输出
修改如下:
#include
#include
#include
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*Linklist;
void CreateList(Linklist &L,int n)
{
int i;
LNode *p;
L=(Linklist)malloc(sizeof(LNode));
L->next=NULL;
for(i=n;i>0;i--)
{
p=(Linklist)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
}
int ListInsert(Linklist &L,int i,int e)
{
Linklist s,p;
p=L;
int j=0;
while(p&&j{
L=L->next;
++j;
}
if(!p||j>i-1)
return ERROR;
s=(Linklist)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return OK;
// free(s);
}
void print(Linklist L)
{
L = L->next;
while(L)
{
printf("%d\t",L->data);
L=L->next;
}
}
int main()
{
Linklist La;
int i,n,e;
scanf("%d",&i);
CreateList(La,i);
scanf("%d",&n);
scanf("%d",&e);
ListInsert(La,n,e);
print(La);
return 0;
}
-------------------------------
当然此程序还有很大错误,比如只能ListInsert的时候没有连接数据,就是最后数据丢失了。。
CreateList的时候用的方式是头插入数据,最后打印的数据是倒过来的。。
------------------------------------------------------------
这是添加了free的:

#include
#include
#include
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*Linklist;
void CreateList(Linklist &L,int n)
{
int i;
LNode *p;
L=(Linklist)malloc(sizeof(LNode));
L->next=NULL;
for(i=n;i>0;i--)
{
p=(Linklist)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
}
int ListInsert(Linklist &L,int i,int e)
{
Linklist s,p;
p=L;
int j=0;
while(p&&j{
L=L->next;
++j;
}
if(!p||j>i-1)
return ERROR;
s=(Linklist)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return OK;
// free(s);
}
void print(Linklist L)
{
L = L->next;
while(L)
{
printf("%d\t",L->data);
L=L->next;
}
}
void MyFree(Linklist L)
{
Linklist p;
while(L)
{
p = L;
L = L->next;
free(p);
p = NULL;
}
}
int main()
{
Linklist La;
int i,n,e;
scanf("%d",&i);
CreateList(La,i);
scanf("%d",&n);
scanf("%d",&e);
ListInsert(La,n,e);
print(La);
MyFree(La);
return 0;
}来自:求助得到的回答
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯