尝试将结果存储在2D数组中

时间:2015-09-06 14:07:49

标签: c arrays

尝试存储读取符合条件的文件的结果,在这种情况下,停止距离指定的纬度和经度小于1000米。我一直收到分段错误。下面是引起麻烦的代码,下面是它的具体部分......

    void check_stops(char *array[200][3], double home_lat, double home_lon)
{
  char *location_type;
  char *parent_station;
  char *stop_id;
  char *stop_code;
  char *stop_name;
  char *stop_description;
  double stop_lat;
  double stop_lon;
  char *zone_id;
  int distance;

  const char delimiters[] = ",";
  char* running;

  int count = 0;
  int col = 0;
  int row = 0;

  FILE *fp;
  fp = fopen("stops.txt", "r");

  if (fp != NULL)
  {
    char line[BUFSIZ];

    while (fgets(line, sizeof(line), fp) != NULL)
    {
      if(count > 1)
      {
        char stringcopy[sizeof(line)];
        strcpy(stringcopy, line);

        running = stringcopy;

        /*
        The code below assumes it knows where the lat and lon are in the CSV file.
        This method will not work with GTFS files from other public transport agencies
        since the order of the fields will be different.
        */

        separatestring(&running, delimiters);                         //removes location_type from stringcopy
        separatestring(&running, delimiters);                         //removes parent_station from stringcopy
        stop_id     = separatestring(&running, delimiters);           //gets stops_id
        separatestring(&running, delimiters);                         //removes stop_code from stringcopy
        stop_name   = separatestring(&running, delimiters);           //gets stop_name
        separatestring(&running, delimiters);                         //removes stop_description from stringcopy
        stop_lat    = atof(separatestring(&running, delimiters));     //gets stop_lat
        stop_lon    = atof(separatestring(&running, delimiters));     //gets stop_lon

        distance = haversine(stop_lat, stop_lon, home_lat, home_lon); //calculates distance between stop location and home location
        char p = distance;
        char * d = &p;

        if(distance <= 1000)
        {
          array[row][col] = stop_id;
          array[row+1][col] = stop_name;
          array[row+2][col] = d;

          col++;

        }
       }
        count++;**
      }
     }

      fclose(fp);
       }

问题出现在这段代码中,每当我删除它时,它都可以正常工作(省略其他与此相关的代码)但是当我把它放入时停止工作......

        if(distance <= 1000)
    {
      array[row][col] = stop_id;
      array[row+1][col] = stop_name;
      array[row+2][col] = d;

      col++;

    }
   }
  count++;**
}

编辑:

固定!谢谢你们

1 个答案:

答案 0 :(得分:1)

根据经验,分段错误通常指向对存储器的错误访问,例如缓冲区溢出的情况。你最终破坏了内存内容,并且不再清楚你的程序会做什么 - 只是在那之后看起来很糟糕。您应该查找如何引用和为数组赋值。

在您的特定情况下,您将二维字符串数组定义为200x3矩阵。此外,对于距离<1的每一行,计数器int col递增。千米。据推测,您阅读的文件不仅仅是3行。

但是,您将值指定为

array[row][col] = stop_id;

这似乎注定要超出为内存中的数组保留的空间,因此是一个段错误:对于第四次命中,此代码等于array[row][3],但array只有3个列

您确定,您不想将其引用为

array[col][row]=stop_id;
array[col][row+1]=stop_name;
array[col][row+2]=d;