天生我才の 2022-01-30 11:14 采纳率: 100%
浏览 22
已结题

有关数组和结构体的代码,看不出来哪里有问题,vs可以运行但会中断

问题遇到的现象和发生背景

运行中断但并没有报错

问题相关代码,请勿粘贴截图
#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;
}

运行结果及报错内容

img

我的解答思路和尝试过的方法
我想要达到的结果

让每个教师的第五名学生的成绩为正常范围

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2022-01-30 11:52
    关注

    问题见注释处,供参考:

    #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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 2月7日
  • 已采纳回答 1月30日
  • 创建了问题 1月30日

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?