m0_53302355 2021-12-04 21:49 采纳率: 100%
浏览 19
已结题

关于数组溢出的问题以及相关问题


#include<iostream>
#include<string>
using namespace std;
struct student {
    string name;
    int score;
};
struct teacher {
    string tname;
    struct student Arry[5];
};
void allocatspace(struct teacher tarry[2], int len)
{
    string nameseed = "ABCDE";
    for (int i = 0; i <= len; i++)
    {
        tarry[i].tname = "teacher_";
        tarry[i].tname += nameseed[i];
        for (int j = 0; j < 5; j++)
        {
            tarry[i].Arry[j].name = "student_";
            tarry[i].Arry[j].name += nameseed[j];
            tarry[i].Arry[j].score = rand()%60+40;
        }
    }
}
void printfInfo(struct teacher tarry[2], int len){
    for (int i = 0; i < len; i++)
    {
        cout << "老师数据" << tarry[i].tname << endl;
        for (int j = 0; j < 5; j++)
        {
            cout << "学生数据" << tarry[i].Arry[5].name << endl;
            cout << tarry[i].Arry[5].score;
        }
    }
}
int main(){
    struct teacher tarry[2];
    int len = sizeof(tarry) / sizeof(tarry[0]);
    allocatspace(tarry, len);
    printfInfo(tarry, len);
    return 0;

}

这个代码为什么编译器会显示数组溢出啊

  • 写回答

1条回答 默认 最新

  • 关注

    第34行35行那么写Arr[5]数组越界了,修改如下:

    void printfInfo(struct teacher tarry[2], int len){
        for (int i = 0; i < len; i++)
        {
            cout << "老师数据" << tarry[i].tname << endl;
            for (int j = 0; j < 5; j++)
            {
                cout << "学生数据" << tarry[i].Arry[j].name << endl;
                cout << tarry[i].Arry[j].score;
            }
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月13日
  • 已采纳回答 12月5日
  • 创建了问题 12月4日

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题