C++ 编码错在哪里

来源:百度知道 编辑:UC知道 时间:2024/09/18 06:04:15
这段编码编译时没有错误,但是运行时就会出错,为什么?

“myfun.h”文件中的编码:
struct node
{int date;
node*next;
};

void Createlist(node * & head)
{node*s,*p;
s=new node;
p=new node;
cin>>s->date;
while(s->date!=0)
{if(head==NULL) head=s;
else p->next=s;
p=s;
s=new node;
cin>>s->date;
}
p->next=NULL;
delete s;
return;
}

void Showlist(node*head)
{cout<<"now the items are:\n";
while(head->next!=NULL)
{cout<<head->date<<'\t';
head=head->next;
}
cout<<endl;
}

“建立和遍历链表.cpp”文件中的代码:
#include<iostream.h>
#include"myfun.h"

void main()
{node *k;
Createlist(k);
Showlist(k);
}

编译时不会出错,运行时会出错退出,调试时显示“Unhandled exception in 建立和遍历链表.exe:oxC0000005:access Violation”,指向“while(head->nex

void main()
{node *k;
Createlist(k);
Showlist(k);
}

让k=0,也就是
void main()
{node *k = 0;
Createlist(k);
Showlist(k);
}

因为你的CreateList函数中判断传进来的head是不是0,您没有对它初始化,局部变量默认不会被初始化为0的。

head->date
该为:
head.date

提示这个错误的主要原因是你的内存地址为空,你的head如果为NULL的话,那么就head->next就一定没有什么意义了,所以会提示你的内存操作有问题。

建议改为if(head != NULL)

void Createlist(node* & head)
{node*s,*p;
s=new node;
p=new node;
cin>>s->date;
s->next =NULL; //注意这里
head=s; //注意这里
while(s->date!=0)
{ //注意这里
p->next=s;
p=s;
s=new node;
cin>>s->date;
}
p->next=NULL;
delete s;
return;
}