代码之家  ›  专栏  ›  技术社区  ›  Sandipan

C中的气泡排序显示分段错误

  •  -2
  • Sandipan  · 技术社区  · 6 年前

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

    #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:警告:传递参数1 of_ swap_使指针从整数而不进行强制转换[-wint conversion]

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

    sort.c:20:16:注意:预期的__int*_,但参数的类型为__int_

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

    sort.c:37:28:警告:传递参数2 of__swap__使得指针从整数开始,而不进行强制转换[-wint conversion]

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

    sort.c:20:24:注意:预期的__int*_,但参数的类型为__int_

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

    当我运行程序时,它正在接受输入,但之后它将显示 segmentation fault (core dumped)

    谢谢你的帮助。

    1 回复  |  直到 6 年前
        1
  •  2
  •   tmlen    6 年前

    这个 swap() 函数接受指针,因此需要像 swap(&arr[a], &arr[b]); .

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

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

    还有变量 a b 未初始化。对于泡沫排序,需要进行比较和交换 i i+1 ,为了 0 size-2 .