#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_SIZE 100
我正试图根据点到原点的距离快速排序一个二维点数组,但我的代码在第一个点之后点击了a
Seg fault
。typedef struct point{
double x;
double y;
double dist;
} point;
void sortpoints(point arr[], int low, int high);
void printpoints(point arr[], int n);
Sortpoints只是根据
scanf
的值排序Point structs
数组的快速排序操作void sortpoints(point arr[], int low, int high){
int piv, i, j;
piv = low;
i = low;
j = high;
point box;
if(low < high){
while(i<j){
while((arr[i].dist)<=(arr[piv].dist) && i<= high)
i++;
}
while((arr[j].dist) > (arr[piv].dist) && j>= low)
j--;
}
if(i<j){
box = arr[i];
arr[i] = arr[j];
arr[j] = box;
}
box = arr[j];
arr[j] = arr[piv];
arr[piv] = box;
sortpoints(arr, low, j-1);
sortpoints(arr, j+1, high);
}
Printpoints只是按点与原点的距离顺序打印点
void printpoints(point arr[], int n){
int i; for(i = 0; i <= n; i++){
printf("(%.2lf, %.2lf)\n", arr[i].x, arr[i].y);
}
}
用户在表单中输入点数和点数值(point.x,point.y)
int main(){
point pointa;
point pointarray[MAX_SIZE];
int n=0;
printf("how many points would you like to enter?\n");
scanf("%d", &n);
if(n<MAX_SIZE){
int i;
for(i=0; i<n ; i++){
scanf("(%lf,%lf)", &pointa.x, &pointa.y);
pointa.dist = sqrt(pointa.x*pointa.x + pointa.y*pointa.y);
pointarray[i] = pointa;
}
sortpoints(pointarray, 0, n-1);
printpoints(pointarray, n);}
else{
printf("sorry, not a valid array size\n");
}
return 0;
}
最佳答案
我有堆栈溢出。
您的程序调用函数sortpoints
,并调用自身(sortpoints
调用sortpoints
)。但我看不出sortpoints
必须停在哪里!
因此,j-1
将变为空,arr[j]
完全无效。
关于c - 段错误,但我不知道为什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20506769/