这里我已经按升序对数组进行了排序。现在我只想打印排序数组的第二个元素。下面的代码打印未排序数组的第二个元素。我能做些什么?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n,b[n],i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<n;j++)
{
if(b[i]>b[j])
{
int a=b[i];
b[i]=b[j];
b[j]=a;
}
}
}
printf("%d",b[1]);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
最佳答案
问题是
int n,b[n],i,j;
当您声明 b[n]
时,n
是不确定的,它可能具有任何垃圾值,因此可能会在后续阶段导致 UB。
从用户处获取n
后声明b
。
int n,i,j;
scanf("%d",&n);
int b[n]; //or int *b = malloc(sizeof(int)*n); and later do free(b);
关于c - 如何只打印排序数组的第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438475/