鱼C论坛

 找回密码
 立即注册
查看: 151|回复: 1

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

[复制链接]
发表于 2024-3-20 19:34:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#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;
       
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-3-20 19:34:27 | 显示全部楼层
问题出在代码中没有为head指针分配内存空间。在list类的构造函数中,应该为head指针动态分配一个stu结构体的内存空间。修改后的代码如下:

  1. #include <iostream>
  2. using namespace std;
  3. typedef struct Student{
  4.     int score;
  5.     Student* next;
  6. }stu;

  7. class list{
  8. private:
  9.     stu* head;

  10. public:
  11.     list(){
  12.         head = new stu(); // 为head指针分配内存空间
  13.         head->next = NULL; // 初始化为空链表
  14.     }
  15.    
  16.     ~list(){
  17.     }
  18.    
  19.     void add(int nu){
  20.         stu* stud = new stu();
  21.         stud->score = nu;
  22.         stud->next = NULL;
  23.         head->next = stud;
  24.         head = head->next;
  25.     }
  26.    
  27.     void display(){
  28.         stu* temp = head->next;
  29.         while(temp != NULL){
  30.             cout << temp->score << " ";
  31.             temp = temp->next;
  32.         }
  33.     }
  34. };

  35. int main(){
  36.     list mylist;
  37.     mylist.add(90);
  38.     mylist.add(80);
  39.     mylist.add(70);
  40.     mylist.display();
  41.     return 0;
  42. }
复制代码


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


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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 01:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表