#include<iostream>
using namespace std;
struct stu
{
string sname;
int score;
};
struct teacher
{
string tname;
struct stu sarray[5];
};
void allocatespace(struct teacher tarray[],int len)
{
string nameseed = "ABCDE";
for (int i = 0;i < len;i++)
{
tarray[i].tname = "teacher_";
tarray[i].tname += nameseed[i];
for (int j = 0;j < 5;i++)
{
srand((int)time(0));
tarray[i].sarray[j].sname = "student_";
tarray[i].sarray[j].sname += nameseed[j];
tarray[i].sarray[j].score = rand() % 100;
}
}
}
void print(struct teacher tarray[], int len)
{
for (int i = 0;i < len;i++)
{
cout <<"第" << i + 1 << "老师的姓名:" << tarray[i].tname << endl;
for (int j = 0;j < len;j++)
{
cout << "他的第" << j + 1 << "个学生的姓名是:" << tarray[i].sarray[j].sname << "他的成绩是:" << tarray[i].sarray[j].score << endl;
}
}
}
int main()
{
struct teacher tarray[3];
int len = sizeof(tarray) / sizeof(tarray[0]);
allocatespace(tarray, len);
print(tarray, len);
system("pause");
return 0;
}
0x00007FFECFC71400 (vcruntime140d.dll)处(位于 Project1.exe 中)引发的异常: 0xC0000005: 读取位置 0xFFFFFFFFFFFFFFFF 时发生访问冲突。
总是显示在 struct teacher tarray[3]; 这一行出问题
根据网上用了逐行运行确定出错位置并将结构体初始化,还是没有作用
修改后正常运行
第20行
for (int j = 0;j < 5;i++)
这里应该是j++
另外一个就是 srand((int)time(0));应该放到main函数里,不能放到for循环里,否则每次的随机数是一样的
#include<iostream>
using namespace std;
struct stu
{
string sname;
int score;
};
struct teacher
{
string tname;
struct stu sarray[5];
};
void allocatespace(struct teacher tarray[],int len)
{
string nameseed = "ABCDE";
for (int i = 0;i < len;i++)
{
tarray[i].tname = "teacher_";
tarray[i].tname += nameseed[i];
for (int j = 0;j < 5;j++)
{
tarray[i].sarray[j].sname = "student_";
tarray[i].sarray[j].sname += nameseed[j];
tarray[i].sarray[j].score = rand() % 100;
}
}
}
void print(struct teacher tarray[], int len)
{
for (int i = 0;i < len;i++)
{
cout <<"第" << i + 1 << "老师的姓名:" << tarray[i].tname << endl;
for (int j = 0;j < len;j++)
{
cout << "他的第" << j + 1 << "个学生的姓名是:" << tarray[i].sarray[j].sname << "他的成绩是:" << tarray[i].sarray[j].score << endl;
}
}
}
int main()
{
srand((int)time(0));
struct teacher tarray[3];
int len = sizeof(tarray) / sizeof(tarray[0]);
allocatespace(tarray, len);
print(tarray, len);
system("pause");
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!