运行中断但并没有报错
#include<iostream>
using namespace std;
struct Student
{
int Sname;
int score;
};
struct Teacher
{
string Tname;
struct Student stu[5];
};
void allocatespace1(struct Teacher tArray[])
{
string nameseed = "ABCDE";
for (int i = 0; i < 3; i++)
{
tArray[i].Tname = "Teacher_";
tArray[i].Tname += nameseed[i];
for (int j = 1; j < 6; j++)
{
tArray[i].stu[j].Sname =j;
tArray[i].stu[j].score = rand() % 100 + 1;
}
}
}
int main()
{
struct Teacher tArray[3];
allocatespace1(tArray);
for (int k = 0; k < 3; k++)
{
cout << "teacher name:" << tArray[k].Tname << endl;
for (int m = 1; m < 6; m++)
{
cout << "student name:" << tArray[k].stu[m].Sname << endl;
cout << "student score:" << tArray[k].stu[m].score << endl;
}
}
system("pause");
return 0;
}
让每个教师的第五名学生的成绩为正常范围
问题见注释处,供参考:
#include<windows.h>
#include<iostream>
using namespace std;
struct Student
{
int Sname;
int score;
};
struct Teacher
{
string Tname;
struct Student stu[5]; //这里定义了 5 个学生的数组,下标 0 - 4
};
void allocatespace1(struct Teacher tArray[])
{
string nameseed = "ABCDE";
for (int i = 0; i < 3; i++)
{
tArray[i].Tname = "Teacher_";
tArray[i].Tname += nameseed[i];
for (int j = 0; j < 5; j++) //for (int j = 1; j < 6; j++) 这里循环下标1 - 5,下标 5 越界
{
tArray[i].stu[j].Sname = j;
tArray[i].stu[j].score = rand() % 100 + 1;
}
}
}
int main()
{
struct Teacher tArray[3];
allocatespace1(tArray);
for (int k = 0; k < 3; k++)
{
cout << "teacher name:" << tArray[k].Tname << endl;
for (int m = 0; m < 5; m++) //for (int m = 1; m < 6; m++) 这里循环下标1 - 5,下标 5 越界
{
cout << "student name:" << tArray[k].stu[m].Sname << endl;
cout << "student score:" << tArray[k].stu[m].score << endl;
}
}
system("pause");
return 0;
}