0

试图计算点数组中最左边的点,程序炸毁了我(分段错误(核心转储)错误)。

这是界面:

//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

我很确定这是发送指针而不是数组的实际副本的问题(诅咒c !!),我的问题是问题到底出在哪里,我该如何解决?

4

1 回答 1

4

在代码的原始版本中,您的函数leftmostPoint()应该返回 anint但您返回 a struct Point。编译器应该抱怨这个。 (此后代码已更新为返回struct Point.)

调用:

struct Point hull = leftmostPoint(points, numPoints);

表示问题出在 的声明中leftmostPoint(),它应该返回 astruct 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];
}

或该主题的变体。

于 2013-10-07T01:39:16.817 回答