我试图编写一个使用指针进行气泡排序的代码。 它给我没有错误,但结果产生随机数字或“分段错误”消息。 请问您是否可以查看我的代码并说出错位置?使用指针的C中的气泡排序
#include <stdio.h>
int * input(int n);
void print(int *ptr, int n);
int * bubble_sort(int *ptr, int n);
void swap(int *a,int *b);
int main(){
int n;
printf("Enter the number of the elements to be sorted:\n");
scanf("%d",&n);
int *ptr;
ptr = input(n);
print(ptr,n);
int *ptr_sort;
ptr_sort = bubble_sort(ptr,n);
// bubble_sort(ptr,n);
print(ptr_sort,n);
// print(ptr,n);
return 0;
}
int * input(int n){
int i;
int array[n];
int *ptr;
ptr = array;
for(i=0;i<n;i++){
printf("Enter element %d value: \n", i+1);
scanf("%d",ptr+i);
}
return ptr;
}
void print(int *ptr, int n){
int i;
for(i=0;i<n;i++)
printf("%d\t",*(ptr+i));
printf("\n");
}
int * bubble_sort(int *ptr, int n){
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
if(*(ptr+j)>*(ptr+j+1))
swap((ptr+j),(ptr+j+1));
return ptr;
}
void swap(int *a,int *b){
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
我尝试了一些调试,valgrid(这我不是很用),我收到的仅仅是第一打印完成后的以下信息:这一次后
==2318== Conditional jump or move depends on uninitialised value(s)
==2318== at 0x400803: bubble_sort (ex18_buble_sort.c:58)
==2318== by 0x40065D: main (ex18_buble_sort.c:21)
==2318==
==2318== Invalid write of size 4
==2318== at 0x40088F: swap (ex18_buble_sort.c:68)
==2318== by 0x40083B: bubble_sort (ex18_buble_sort.c:59)
==2318== by 0x40065D: main (ex18_buble_sort.c:21)
==2318== Address 0xf0000000f is not stack'd, malloc'd or (recently) free'd
和许多其他的消息,但我猜一切都从这里开始。所以最有可能的问题是在bubble_sort函数中的某个地方。
请帮忙!
'int array [n];'是一个局部数组,它将在函数input的执行结束后被销毁。修复它包括使用一个全局数组,为它动态分配内存并使用'static int array [n];' –
简单地用int * array = malloc(n * sizeof(int))替换数组定义;''似乎修复'valgrind'报告的所有无效读/写操作。你也必须'释放'它虽然... – dragosht