为什么会出现“多个测试用例”错误?

时间:2019-10-06 11:05:05

标签: c++

我已经编写了消除数组中最大2个元素的代码,但是该代码为testcase > 1提供了垃圾值。为什么?

输入:

no of TestCase
size of array
elements of array

排序功能:

int sort_asc(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            if(arr[j]<arr[i])
            {
                int temp;
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
}

int main() {
    //code
    int test;
    cin>>test;
    while(test--){
        //taking size and array as inputs
        int size;
        cin>>size;
        int a[size];
        cin>>a[size];
        for(int i=0;i<size;i++){
            cin>>a[i];
        }
        //sorting the array
        sort_asc(a,size);
        //printing the output discarding last 2 elements of the array
        for(int i=0;i<size-2;i++){
            cout<<a[i]<<" ";
        }
        cout<<"\n";
    }
    return 0;
}

预期:

12 23 28 43 44 59 60 68 70 85 88 92 124 125 136 168 171 173 179 199 212 
230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 394 414 
422 427 430 435 457 493 506 527 531 538 541 546 568 583 650 691 730 737 751 
764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 927  930 957

我的输出:

12 23 28 43 44 59 60 68 70 81 85 88 92 124 125 136 168 171 173 179 199  212 230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 394 414 422 427 430 435 457 493 506 527 531 538 541 546 568 583 650 691 730 737 751 764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 930 957

1 个答案:

答案 0 :(得分:0)

VLA(可变长度数组)是无效的C ++代码。某些编译器可以接受,但是仍然无效。

但这不是您的主要问题。您产生了超出范围的错误。数组索引以0开头。最后一个元素的位置为size-1。所以你的声明

cin>>a[size];

将写到数组末尾。产生不确定的行为。

我不确定,为什么要放置该语句,但是之后,所有未定义的事情都可能发生,并且很有可能会发生。