指针作为结构成员

时间:2021-04-22 13:27:33

标签: c++

struct student{
string name;
int sNumber,*examGrade;
};

int main(){

int i,k,l;
cout<< "number of student in program:";
cin >>l;
cout<< "number of exam in program:";
cin >>k;
student stName[100], examNum[100];


for(int i=1;i<=l;i++){

    student stdnt;
    cout<<i<<".student name: ";
    cin>>stdnt.name;
    cout<<i<<".student number: ";
    cin>>stdnt.sNumber;
    stName[i] = stdnt;

    for(int j=1 ; j<=k; j++){

        student * test = new student();
        cout<<i<<". student"<<j<<".grade: ";
        cin>>*test->examGrade;
        examNum[j]= *test;

    }

    }


return 0;
}

我刚开始编码。我写的代码中无法完成该功能是什么原因? 如何为指针结构赋值? 我想我在访问指向结构成员的指针时犯了一个错误。

1 个答案:

答案 0 :(得分:0)

您在未初始化的情况下使用了 test->examGrade。在取消引用之前为其分配有效的指针。

    for(int j=1 ; j<=k; j++){

        student * test = new student();
        cout<<i<<". student"<<j<<".grade: ";
        test->examGrade = new int; // add this, for example
        cin>>*test->examGrade;
        examNum[j]= *test;

    }