[英]Why does it give a “multiple test case” error?
I've written the code for eliminating the largest 2 elements of an array, but this code gives junk value for testcase > 1
.我已经编写了用于消除数组的最大 2 个元素的代码,但是此代码为
testcase > 1
提供了垃圾值。 Why?为什么?
Input:输入:
no of TestCase
size of array
elements of array
Sorting function:排序 function:
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;
}
Expected:预期的:
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
My output:我的 output:
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
A VLA (variable length array) is invalid C++ code. VLA(可变长度数组)是无效的 C++ 代码。 It is tolerated by some compilers, but it is still invalid.
一些编译器可以容忍它,但它仍然无效。
But that is not your main problem.但这不是你的主要问题。 You produced an out of bound error.
您产生了超出范围的错误。 An array index starts with 0. The last element is at position size-1.
数组索引从 0 开始。最后一个元素位于 position 大小为 1。 So your statement
所以你的陈述
cin>>a[size];
will write past the end of your array.将写到数组的末尾。 Producing undefined behavior.
产生未定义的行为。
I am not sure, why you put the statement at all, but after that, anything undefined can and most probably will happen.我不确定你为什么要发表声明,但在那之后,任何未定义的事情都可能而且很可能会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.