请大家帮个忙,关于c++中结构指针的问题

zcl198715 2008-03-13 08:38:11

//本程序是为了建一个链表!
//并完成相关操作
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
student *next;
};
void creat(student *first)//建立链表,并输入数据
{
student *current;
int a;
first=current=new student;
cout<<"输入姓名:\n";
cin>>current->name;
cout<<"继续输入(yes==1,no==0)"<<'\n';
cin>>a;
while(a)
{
current=current->next=new student;
cin>>current->name;
cout<<"继续输入(yes==1,no==0)"<<'\n';
cin>>a;
}
current->next=0;
cout<<"输入完成!\n";
}
void print(student *first)//输出
{
student *current;
current=first;
while(current!=0)
{
cout<<current->name<<'\n';
current=current->next;
}
}
void destroy(student *first)//销毁
{
student *current;
while(first!=0)
{
current=first->next;
delete first;
first=current;
}
cout<<"删除成功\n";

}
int main()
{
student *first=NULL;//为什么要将first赋值为NULL,可不可以不赋值啊?
creat(first);
print(first);//通过测试,我发现first为空,为什么?也就是说,first=0
destroy(first);
return 0;
}

希望大家能给些帮助,不胜感谢!
...全文
50 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
lsldd 2008-09-25
  • 打赏
  • 举报
回复
void creat(student* &first)//注意,加上&,表示传引用!才能在函数里面改变first指针的值!

student *first=NULL;//指针一定要初始化!否则是野指针!没有初始化,无法预料他指向哪里!

64,849

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧