Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么它会给出一个“答案”;“多个测试用例”;错误?_C++ - Fatal编程技术网

C++ 为什么它会给出一个“答案”;“多个测试用例”;错误?

C++ 为什么它会给出一个“答案”;“多个测试用例”;错误?,c++,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

我已经编写了消除数组中最大的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 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
(可变长度数组)是无效的C++代码。某些编译器可以容忍它,但它仍然无效

但这不是你的主要问题。您产生了一个越界错误。数组索引以0开头。最后一个元素位于位置size-1。那么你的声明呢

cin>>a[尺寸]

将写入超过数组末尾的内容。产生未定义的行为

我不确定,你为什么要写这个声明,但在那之后,任何未定义的事情都可能发生,而且很可能会发生

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