You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++运行时检查失败#2:变量周围堆栈损坏问题求助

解决Run-Time Check Failure #2:堆栈损坏问题

你的问题根本不是数组空间不够,而是数组越界访问——你一直在读写超出数组范围的内存地址,直接破坏了堆栈结构,导致运行时错误。

核心错误点

你定义的二维数组passes[sixteen][sixteen]索引范围是0~15(因为数组大小是16),但在get_data、NFL、NCAA函数里,你错误地用sixteen(值为16)作为索引:

  • passes[sixteen][i]:访问第17行(超出数组最大行索引15)
  • passes[i][sixteen]:访问第17列(超出数组最大列索引15)

而且每个比赛只需要两个传球数据:完成数和尝试数,二维数组第二维根本不需要16个元素,改成2个足够,还能节省内存。

修正后的关键代码片段

1. 修正get_data函数的输入逻辑

void get_data(int games[], float passes[][2], float tds[], float Int[], float yards[], int sixteen)
{
    for (int i = 0; i < sixteen; i++)
    {
        cout << "\n*****************************************\n";
        cout << "\nCompletions in game " << games[i] << ": ";
        cin >> passes[i][0];  // 用第0列存完成传球数
        while (passes[i][0] < 0) {
            cout << "\nCompletions cannot be negative. Try again.";
            cout << "\nCompletions in game " << games[i] << ": ";
            cin >> passes[i][0];
        }
        cout << "\nPass attempts in game " << games[i] << ": ";
        cin >> passes[i][1];  // 用第1列存传球尝试数
        while (passes[i][1] < 0) {
            cout << "\nPass attempts cannot be negative!\n";
            cout << "\nPass attempts in game " << games[i] << ": ";
            cin >> passes[i][1];
        }
        // 其余校验逻辑保持不变
    }
}

2. 修正NFL函数的计算逻辑

void NFL(int games[], float passes[][2], float tds[], float Int[], float yards[], int sixteen, float rating[]) {
    float a, b, c, d;
    for (int i = 0; i < sixteen; i++) {
        a = (((passes[i][0] / passes[i][1]) * 100) - 30) / 20;
        b = ((tds[i] / passes[i][1]) * 100) / 5;
        c = (9.5 - ((Int[i] / passes[i][1]) * 100)) / 4;
        d = ((yards[i] / passes[i][1]) - 3) / 4;
        rating[i] = (a + b + c + d) / .06;
        cout << " " << a << " " << b << " " << c << " " << d;
    }
}

3. 修正NCAA函数的计算逻辑

void NCAA(int games[], float passes[][2], float tds[], float Int[], float yards[], int sixteen, float rating[]) {
    float a, b, c, d;
    for (int i = 0; i < sixteen; i++) {
        a = (passes[i][0] / passes[i][1]) * 100;
        b = (tds[i] / passes[i][1]) * 100;
        c = (Int[i] / passes[i][1]) * 100;
        d = yards[i] / passes[i][1];
        rating[i] = a + (3.3 * b) - (2 * c) + (8.4 * d);
        cout << a << " " << b << " " << c << " " << d;
    }
}

4. 修正主函数里的数组定义

把二维数组改成需要的大小:

float passes[sixteen][2];  // 第二维只需要2个元素

额外建议

定义全局常量替代魔法数字,避免索引错误:

const int sixteen = 16;
const int pass_stats_count = 2;

内容的提问来源于stack exchange,提问作者tamuljin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:15:55