将输入输入c ++数组时出现运行时错误

时间:2018-03-15 16:39:50

标签: c++ combinatorics

我正在编写一个编程问题(Uva#11330 https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=2305&mosmsg=Submission+received+with+ID+20947216)并且我的代码传递了给出的测试用例但在我提交时一直给我一个运行时错误,我无法弄清楚原因。它在我的结尾完美运行。我把问题缩小到我输入的地方。关于它为什么给我这个错误的任何想法?

[编辑]更改了数组声明。现在的问题是,即使我仍然通过了所有的测试用例,自动判断仍然是错误的。还有什么想法吗?

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;



int main(){
    int numTestCases;
    int numShoes;
    int l, r;
    int numSwaps;
    int leftIndexes[10005];
    int rightIndexes[10005];
    int leftShoes[10005];
    int rightShoes[10005];
    cin >> numTestCases;

    for(int i = 0; i < numTestCases; i++){

        numSwaps = 0;



        cin >> numShoes;

        for(int j = 0; j < numShoes; j++){
            cin >> l >> r;
            leftIndexes[l-1] = j;
            rightIndexes[r-1] = j;
            leftShoes[j] = l-1;
            rightShoes[j] = r-1;
        }

        for(int j = 0; j < numShoes; j++) {
            if(leftIndexes[j] != rightIndexes[j]) {
                int aIdx = rightIndexes[j];
                rightShoes[aIdx] = rightShoes[leftIndexes[j]];
                rightIndexes[rightShoes[leftIndexes[j]]] = aIdx;                
                numSwaps++;
                //cout << ret << endl;
            }
        }
        cout << numSwaps << endl;

    }
    return 0;
}

1 个答案:

答案 0 :(得分:3)

cin >> numShoes;

int leftShoes[numShoes];
int rightShoes[numShoes];
int leftIndexes[numShoes];
int rightIndexes[numShoes];

不。

数组维度应为编译时常量。您无法使用用户输入调整数组大小。

使用new[]创建一个动态内存块,或者让自己变得更好vector

然后,将错误检查添加到您的所有I / O中,以便您知道您没有尝试访问固定数组/向量中的无意义索引。

相关问题