视频教程中结构体与共用体一张 链表课程习题 但是最后输出没有达到预期目的
#include "stdafx.h"#include <iostream>
typedef struct Student{
unsigned short index;
unsigned short grade;
Student* next;
};
int _tmain(int argc, _TCHAR* argv[])
{
//input all information nutill input index-0
Student* head = nullptr;
Student* ptr = nullptr;
while (true)
{
Student* p;
Student* getStudent();
p = getStudent();
if (p->index == 0)
{
break;
}
if (head == nullptr)
{
head = p;
}
if (head != nullptr&&head->next == nullptr)
{
head->next = p;
ptr = p;
}
if (ptr != nullptr)
{
ptr->next = p;
ptr = p;
}
}
//output all information
while (head!=nullptr)
{
std::cout << head->index << " " << head->grade << std::endl;
head = head->next;
}
return 0;
}
//method to get Student*
Student* getStudent(){
Student a = {0,0,nullptr};
Student* p =&a;
std::cout << "please input index and grade of a student:";
std::cin >>p->index >> p->grade;
p->next = nullptr;
return p;
}
顶 没有问题描述,没有运行结果,没有错误提示,没人有心情看那一堆 :sad 这是什么方面的知识 {:1_1:}{:1_1:}{:1_1:} :sad:sad Student* getStudent(){
Student a = {0,0,nullptr};
Student* p =&a;
std::cout << "please input index and grade of a student:";
std::cin >>p->index >> p->grade;
p->next = nullptr;
return p;
}
这个函数内部做了一个局部变量Student a,对它进行一些赋值后返回它的地址,接着这个局部变量声明周期结束,于是这个指针指向一个已经死亡的变量,天晓得会出什么问题。
一眼瞄到这个问题,其它的没认真看。
页:
[1]