C++ 作为结构成员的指针 struct学生{ 字符串名; int sNumber,*examGrade; }; int main(){ int i,k,l; cout>l; cout>k; 学生学名[100],考试[100]; 对于(inti=1;i

C++ 作为结构成员的指针 struct学生{ 字符串名; int sNumber,*examGrade; }; int main(){ int i,k,l; cout>l; cout>k; 学生学名[100],考试[100]; 对于(inti=1;i,c++,C++,您使用了test->examGrade,但没有初始化它。请在取消引用之前为它指定有效指针 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:";

您使用了
test->examGrade
,但没有初始化它。请在取消引用之前为它指定有效指针

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

用于(int j=1;j
examGrade
未初始化,
std::vector examGrade;
会更简单。您可以将
student.examGrade
声明为指向
int
的指针。这或多或少是好的。但您不会为这些指针中的任何一个指定有效值。如果您想使用它们为指向
int
的指针赋值,则那些
int
s必须存在,并且您必须设置指向它们的指针。请注意,要在数组声明中指定的数字如果是元素数,那么您的程序最多可以处理99个学生和考试,而不是100个。为什么要将
struct student
examGrade
成员作为指针?在中在任何事件中,都需要显式初始化指针,使其实际指向
int
。例如,
test->examGrade=new int
,然后才能读取
*test->examGrade
的值。通常,创建指针不会神奇地为该指针创建指针对象。
cin>*test->examGrade
试图写入一个不存在的
int
,因此会导致未定义的行为。在
student stName[100]中命名,examNum[100];
是可疑的。你真的想要200
student
s.BTW吗,
student*test
是无用的(而且实际上是泄漏的)。它可能应该是
examGrade=new int[k];
    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;

    }