[英]Segmentation fault with struct array
試圖計算點數組中最左邊的點,該程序對我造成打擊(分段錯誤(核心轉儲)錯誤)。
這是界面:
//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 !!),我的問題是問題到底在哪里,我該如何解決?
在代碼的原始版本中,您的函數leftmostPoint()
應該返回一個int
但是您返回一個struct Point
。 編譯器應該對此抱怨。 (此后,代碼已更新為返回struct Point
。)
調用:
struct Point hull = leftmostPoint(points, numPoints);
指示問題出在leftmostPoint()
的聲明中,該聲明應該返回struct Point
而不是int
。
因此,請通過以下任一方法修復:
struct Point (leftmostPoint(struct Point points[], int numPoints)
{
int smallestX = points[0].x; //take the first point in the list and assume it's smallest
int index = 0;
for (int i= 1; i < numPoints; i++){
if (points[i].x < smallestX){
smallestX = points[i].x;
index = i;
}
}
return points[index];
}
或通過:
int leftmostPoint(struct Point points[], int numPoints)
{
int smallestX = points[0].x; //take the first point in the list and assume its smallest
int index = 0;
for (int i= 1; i < numPoints; i++){
if (points[i].x < smallestX){
smallestX = points[i].x;
index = i;
}
}
return index;
}
我懷疑返回int
的版本更有用。 您需要知道數組中的哪個條目是最左邊的,而不僅僅是條目的值。
您還將注意到paxdiablo將index
設置為零,以避免數組中的第一項是x
值最低的項時返回“隨機”值的可能性。
既然您已經解決了編譯問題,那么下一個問題確實應該是:
numPoints
的值是什么? 您始終可以將打印代碼添加到函數中,以檢查是否獲取了正確的數據:
struct Point (leftmostPoint(struct Point points[], int numPoints)
{
int smallestX = points[0].x; //take the first point in the list and assume it's smallest
int index = 0;
assert(numPoints > 0);
printf("-->> %s: numPoints = %d: index = %d, x = %d\n",
__func__, numPoints, index, smallestX);
for (int i= 1; i < numPoints; i++){
if (points[i].x < smallestX){
smallestX = points[i].x;
index = i;
printf("---- %s: index = %d, x = %d\n", __func__, index, smallestX);
}
}
printf("<<-- %s: index = %d: x = %d\n", __func__, index, points[index].x);
return points[index];
}
或該主題的變體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.