c - C 中的冒泡排序显示段错误

标签 c sorting bubble-sort

我正在编写一个代码来使用冒泡排序对数组进行排序,但它显示了一个我无法解决的错误。代码:

#include<stdio.h>

void swap();
void bubbleSort();
void printArr();

void main()
{
    int n, arr[20];
    printf("\n Enter the number of elements: ");
    scanf("%d",&n);
    printf("\n Enter the elements: ");
    for(int i = 0; i<= n-1; i++)
        scanf("%d",&arr[n]);
    bubbleSort(arr, n);
    printArr(arr, n);  
}

void swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

void bubbleSort(int arr[], int size)
{
    int a, b;
    for(int i=0; i<=size-1; i++)
    {
        if(arr[a] > arr[b])
            swap(arr[a],arr[b]);

    }
 }

void printArr(int arr[], int size)
{
    int i;
    printf("\n Sorted array: ");
    for(i=0; i<=size-1; i++)
        printf(" %d ", arr[i]);
}

当我编译文件时,它显示两个警告,如下所示:

sort.c:在函数“bubbleSort”中:

sort.c:37:21:警告:传递“swap”的参数 1 使指针来自整数而不进行强制转换 [-Wint-conversion]

         swap(arr[a],arr[b]);
              ~~~^~~

sort.c:20:16:注意:预期为“int *”,但参数的类型为“int”

          void swap(int *a, int *b)
                    ~~~~~^

sort.c:37:28:警告:传递“swap”的参数 2 使指针来自整数而不进行强制转换 [-Wint-conversion]

         swap(arr[a],arr[b]);
                     ~~~^~~

sort.c:20:24:注意:预期为“int *”,但参数的类型为“int”

         void swap(int *a, int *b)
                   ~~~~~^

当我运行程序时,它正在接受输入,但之后它显示段错误(核心转储)

感谢您的帮助。

最佳答案

swap() 函数需要指针,因此需要像 swap(&arr[a], &arr[b]); 那样调用。

否则,它会将 int 值作为内存地址(即指针 int*)并尝试访问它们,这会导致段错误,因为程序访问外部它的有效地址范围。

对于冒泡排序,它需要多次迭代数组,直到所有对都处于正确的顺序。

变量ab也未初始化。对于冒泡排序,需要比较并交换 ii+1,其中 i0 > 到 size-2

关于c - C 中的冒泡排序显示段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53969936/

相关文章:

c# - 不寻常的 for 循环语句

c++ - 如何检测 win32 上的数据卡连接和断开事件?

sorting - 有什么理由来实现我自己的排序算法吗?

sorting - GPU 上的并行冒泡排序

C : Array of strings - Can input only n-1 strings for an input size of n

c - put 函数、指针和字符串如何工作?为什么 strchr() 会在搜索字符之后获取字符?

c - 在声明的 C 字符串上添加 CRLF

r - 使用 ggplot2 根据其大小(即数值)对条形图进行排序

c - 使用 if-else 对 3 个值进行排序的最有效的 C 程序是什么?

C:指向数组的指针和破坏性排序