关于链表的简单问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 16:50:07
源码如下:
int main()
{
struct student{
int age;
struct student *next;
}first;
struct student *head;
struct student *p;

head=&first;
p=head;
p->age=0;
p->next=head;

void add(struct student *point){
struct student c;
c.next=point->next;
point->next=&c;
point->next->age=0;
point=point->next;
}

add(p);

printf("%d\n",p->age);
p=p->next;
printf("%d\n",p->age);

return 0;
}
输出结果为:
0
2293728

而我想要得结果为:
0
0

能帮忙改过来吗?谢谢!
问题已经解决了 谢谢各位!
原因:add(struct student *point)方法在main()内,所以声明的c变量是一个局部变量,调用完add()方法后,c便被释放,point指向的地址便不确定

解决方法:将add(struct student *point)方法放在main()之上,或者将struct student c改为static struct student c

楼下两位的改法都是将c的next域设为NULL

帅哥,你的程序好乱啊!

链表要插入新节点首先要分配内存给他啊!第2个输出是内存地址!

/* 在point后插入一个节点 */
void add(struct student *point)
{
/* 给新节点分配内存 */
point->next = new struct student;

/* 给新节点赋值 */
point->next->age = 0;
point->next->next = NULL;
}

试试看~ ~

void add(struct student *point){
struct student c;
c.next=point->next;
point->next=&c;
point->next->age=0;
point=point->next;
}

point=point->next;后面加上一行看看 加上:
point->next=NULL;