c - 如何只打印排序数组的第二个元素?

标签 c sorting arraylist

这里我已经按升序对数组进行了排序。现在我只想打印排序数组的第二个元素。下面的代码打印未排序数组的第二个元素。我能做些什么?

 #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/

相关文章:

c - 如何安全和/或快速地从 C 内存中的 n 个字节组成一个 int?

c++ - 如何将c/c++编译为ms-dos .com程序?

c++ - 在 C++ 中检查数组的顺序

java - 基于 arraylist 的排序索引的 Hashmap 排序

java - 更改 ArrayList 中对象的字段,然后在下一次迭代中跳过该对象

C - 空指针如何成为常量?

ios - 对 NSMutableArray 进行排序

java - 使用 Hashmap 创建多个 Array 列表

java - 字典困境 : Array vs Arraylist

c - 如何转义utf-8并将utf-8代码转换为字节