首页 文章

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

提问于
浏览
-1

我正在编写一个编程问题(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 回答

  • 3
    cin >> numShoes;
    
    int leftShoes[numShoes];
    int rightShoes[numShoes];
    int leftIndexes[numShoes];
    int rightIndexes[numShoes];
    

    不 .

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

    使用 new[] 创建一个动态的内存块,或者给自己一个不错的 vector .

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

相关问题