codingCat 发表于 2014-9-1 21:41:25

视频教程中结构体与共用体一张 链表课程习题 但是最后输出没有达到预期目的

#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;
}

codingCat 发表于 2014-9-1 21:43:05

川本姨夫 发表于 2014-9-1 23:32:12

没有问题描述,没有运行结果,没有错误提示,没人有心情看那一堆

银屏你我 发表于 2014-9-4 09:59:21

:sad

银屏你我 发表于 2014-9-4 10:00:07

这是什么方面的知识

醉、爱 发表于 2014-9-7 15:21:08

{:1_1:}{:1_1:}{:1_1:}

蚯蚓翔龙 发表于 2014-10-12 22:20:09

:sad:sad

仰望天上的光 发表于 2014-10-12 22:23:22

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]
查看完整版本: 视频教程中结构体与共用体一张 链表课程习题 但是最后输出没有达到预期目的