首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

链表求相助

2013-06-25 
链表求帮助void CreatCustomer(customer *customer1){system(cls)customer *ppcustomer1while (p-n

链表求帮助

void CreatCustomer(customer *customer1){
system("cls");
customer *p;
p=customer1;
while (p->next!=NULL){
p=p->next;
}
p=new customer;
cout << "Please enter the id:\n";
cin >> p->id;
cout << "\nPlease enter the passwords:\n";
cin >> p->password;
p->next=NULL;
cout << "\nCreat new user sucesssfully!\n";
system("pause");
}




customer* customer::Read(){
customer *head,*p1,*p2;
head=p1=new customer;
p2=new customer;
fstream f("customer.txt",ios::in|ios::binary);
if(f.fail()){
cout<<"\nFailed to open the file!\n";
system("pause");
exit(0);
}
f.read((char*)p2,sizeof(customer));
while(!f.eof()){
p1->next=p2;
p1=p2;
p2=new customer;
f.read((char*)p2,sizeof(customer));
}
p1->next=NULL;
free(p2);
f.close();
return head;
}


请问为什么CreatCustomer()一运行立马就程序停止响应。。新人实在找不到错误
[解决办法]
  先说第二段代码,new申请的内存,是用delete来释放的;malloc申请的内存,才是用free释放的,这是必须匹配的,请注意。
  第一段代码中,customer1的含义不明确,据本人估计应该是一个customer的链表的头,即head,你先把用p表示到链表最后一个结点,这时p所指向的内容是链表的一个结点,是有内容的;你又突然重新为p的指向申请一块内存,并且赋值,想当然地认为p就被连接到链表尾了,实际上p是被孤立的,并没有进行作为链表尾结点next的语句描述。
  建议专门写个函数对链表的结点用delete进行删除,否则,new申请的内存会被长期占用,降低cpu的使用效率
[解决办法]
怎么调用CreatCustomer的?调用时传的参数是什么?
    while (p->next!=NULL){
        p=p->next;
    }
很有可能是死循环

热点排行