c++编程时遇到的小问题


#include <iostream>
#include <string>
using namespace std;
struct Student{
    string name;
    int score;
    struct Student *next;
};
int menu()
{
    int choice;
    do
    {
        cout<<"请输入您的选择:"<<endl;
        cout<<"  1.成绩添加"<<endl;
        cout<<"  2.成绩删除"<<endl;
        cout<<"  3.成绩排序"<<endl;
        cout<<"  4.成绩插入"<<endl;
        cin>>choice;
        system("cls");
    }while(choice!=1 && choice!=2 && choice!=3 && choice!=4);
    return choice;
}
struct Student *addScore(struct Student *head,struct Student *latest_node)
{
    int score;
    if(head==NULL){
        Student *head=new Student;
        latest_node=head;
        cout<<head<<endl;
    }
    do
    {
        cout<<head<<endl;
        Student *p=new Student;
        cout<<"请输入姓名:";
        cin>>p->name;
        cout<<"请输入分数(输入负数时停止输入):";
        cin>>p->score;
        score=p->score;
        //system("cls");
        latest_node->next=p;
        //cout<<latest_node<<endl;
        //cout<<latest_node->next<<endl;
        
        latest_node=p;
        p->next==NULL;
    }while(score>=0);
    cout<<"测试"<<endl;
    cout<<&head<<" "<<head->next;
    return latest_node;
}
int main()
{
    Student *head = NULL;
    Student *latest_node = NULL;
    int choice = menu();
    switch(choice)
    {
        case 1:{
            latest_node=addScore(head,latest_node);
            break;
        }
        case 2:{
            break;
        }
        case 3:{
            break;
        }
        case 4:{
            break;
        }
    }
    return 0;
 } 

为什么代码31行和35行的代码运行结果不一样?
head地址为什么在35行变成了0?

img


你目的使用的head一直没有被初始化空间,29行的head 是你新定义的局部变量

29行Student *head=new Student;错了,改为
head=new Student;
你这里重新定义了一个局部变量head,就不是函数参数head了啊