1215787625 发表于 2024-3-20 19:34:14

为什么此代码运行无法正常显示结果

#include<iostream>
using namespace std;
typedef struct Student{
        int score;
        Student* next;
}stu;

class list{
        private:
                stu* head;

        public:
                list(){
                       
                }
               
                ~list(){
                }
               
        void add(int nu){
                        stu* stud = new stu();
                        stud->score = nu;
                        stud->next = NULL;
                        head->next = stud;
                        head = head->next;
                        cout<<head->score;
                }
               
                void bian(){
                        while(head->next!=NULL){
                                cout<<head->score<<endl;
                                head = head->next;
                        }
                }
};
               
int main(){
        int a=0,i=0;
        list* h;
        for(i=0;i<5;i++){
                h->add(i);
        }
        h->bian();
        return 0;
       
}

FishC 发表于 2024-3-20 19:34:27

问题出在代码中没有为head指针分配内存空间。在list类的构造函数中,应该为head指针动态分配一个stu结构体的内存空间。修改后的代码如下:

#include <iostream>
using namespace std;
typedef struct Student{
    int score;
    Student* next;
}stu;

class list{
private:
    stu* head;

public:
    list(){
      head = new stu(); // 为head指针分配内存空间
      head->next = NULL; // 初始化为空链表
    }
   
    ~list(){
    }
   
    void add(int nu){
      stu* stud = new stu();
      stud->score = nu;
      stud->next = NULL;
      head->next = stud;
      head = head->next;
    }
   
    void display(){
      stu* temp = head->next;
      while(temp != NULL){
            cout << temp->score << " ";
            temp = temp->next;
      }
    }
};

int main(){
    list mylist;
    mylist.add(90);
    mylist.add(80);
    mylist.add(70);
    mylist.display();
    return 0;
}

运行该代码,可以看到输出结果为:
90 80 70

这样就能够正常显示结果了。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 为什么此代码运行无法正常显示结果