c++ - 每次我为我的 C++ 程序提供大量输入集时,我的 DOS 都会崩溃

标签 c++ windows dos

我用 C++ 编写了代码,并尝试使用 MinGW 和 TDMGCC 编译器对其进行编译。它编译得很好。但是当我尝试使用这些编译器生成的 .exe 文件并且我为我的程序提供大量输入集时,问题就出现了,我的 DOS 停止工作并说 Windows 已经停止工作。单击“确定”后,它会终止我的执行。我该如何解决。 这是我的代码

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    int t,n,k,c,x,w;
    ofstream myfile;
    myfile.open ("example.txt");
    cin>>t;
    for(w=1;w<=t;w++)
    {
        cin>>n>>k>>c>>x;
        int a[n],b[n],array[n][n];
        for(int i=1;i<=n;i++)
            cin>>a[i];
        for(int i=1;i<=n;i++)
            cin>>b[i];
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                array[i][j]=(a[i]*i+b[j]*j+c)%x;
            }
        }

        int re[1000],z=0;
        if(k>1){
        for(int i=1;i+k-1<=n;i++)
        {
            for(int j=1;j+k-1<=n;j++)
            {
                re[z]=array[i][j]+array[i][j+1]+array[i+1][j]+array[i+1][j+1];

                z++;
            }
        }}

        else
        {
            for(int i=1;i<=n;i++)
            {
                for(int j=1;j<=n;j++)
                {
                    re[z]=array[i][j];
                    z++;
                }
            }
        }


        int lar=re[0];
        for(int i=1;i<z;i++)
        {
            if(re[i]>lar)
                lar=re[i];
        }
        myfile<<"Case #"<<w<<": "<<lar<<endl;
    }
    myfile.close();
    return 0;
}

最佳答案

你有一个基本的差一错误:

    int a[n],b[n],array[n][n];
    for(int i=1;i<=n;i++)
        cin>>a[i];

a有长度 n ,表示有效索引介于 0 之间和 n-1包括的。您正在索引 n 处写入一个值, 已经结束了。

改为像这样构造你的循环:

    for (int i = 0; i < n; i++)
        cin >> a[i];

你所有的循环都显示了这个问题。

此外,如@NathanOliver 所说,使用 std::vector而不是可变长度数组 (VLA)。 VLA 在 C 标准中,但不在 C++ 中。所以你在这里使用它是非标准的。只需添加 #include <vector>并替换

int a[n];

std::vector<int> a(n);

其他一切都可以保持不变。

关于c++ - 每次我为我的 C++ 程序提供大量输入集时,我的 DOS 都会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33218930/

相关文章:

c++ - 给定一组顶点,如何生成边数接近最少的强连通有向图?

c++ - 如何在window系统中读出磁盘驱动序号?

windows - 您将如何模仿普通 DOS 批处理文件中的函数?

c++ - 是否可以假定浮点相等性和不相等性测试是一致且可重复的?

c++ - 函数签名的专用模板

Windows SSH 要求输入密码

x86 - 与 6502 相比,模拟 x86 架构时会出现什么问题?

batch-file - 无法连接以逗号分隔的字符串

c++ - C++变量销毁

c# - 如何控制网络客户端电脑