試圖計算點陣列中最左邊的點,程序在我身上爆炸(分段錯誤(核心轉儲)錯誤)。結構數組的分段錯誤
這裏的接口:
//points.h
#define MAX_POINTS 100
struct Point {
char label;
int x;
int y;
};
int leftmostPoint(struct Point points[], int numPoints);
這裏是leftmostPoint
實現:
//points.c
//get the point with the smallest x value
int leftmostPoint(struct Point points[], int numPoints) {
int smallestX = points[0].x; //assume first point is smallest
int index;
for (int i = 1; i < numPoints; i++) {
if (points[i].x < smallestX) {
smallestX = points[i].x;
index = i;
}
}
return points[index];
}
這裏的地方,奇蹟發生了:
//magic.c
struct Point points[MAX_POINTS];
//build array via standard input (this works, tested by printing the points)
//only 5 points were added in
displayPoint(points[0]); //works
displayPoint(points[4]); //works
struct Point hull;
hull = leftmostPoint(points, numPoints); //this is where the program blows up
我敢肯定它的發送指針的問題而不是數組的實際副本(curse c !!),我的問題是在哪裏問題確切,我該如何解決它?
對不起Jonathan,當我在Stack Overflow中編寫代碼時,這是一個錯字!我的代碼反映了適當的返回值,leftmostPoint()的確返回了一個結構體Point –
當你調用leftmostPoint時,你傳遞了numPoints。該變量在哪裏定義? – Yoctohan
對不起,numPoints是在我讀取用戶輸入了多少點之後在主體中定義的。在這個例子中,numPoints是5. –