我正在编写一个代码来使用冒泡排序对数组进行排序,但它显示了一个我无法解决的错误。代码:
#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*
)并尝试访问它们,这会导致段错误,因为程序访问外部它的有效地址范围。
对于冒泡排序,它需要多次迭代数组,直到所有对都处于正确的顺序。
变量a
和b
也未初始化。对于冒泡排序,需要比较并交换 i
和 i+1
,其中 i
与 0
> 到 size-2
。
关于c - C 中的冒泡排序显示段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53969936/