1

嗨,我正在尝试解析每行有 2 个双打的 txt 文件。在第一行有一个整数,它是 txt 文件的总行数。我有一个双精度的 Nx2 矩阵 COORD[NPOIN][2],我想将每个 txt 行的第一个双精度放入 COORD[IPOIN][0],第二个放入 COORD[IPOIN][1]。下面的代码部分应该能启发你:D

COORD = (double**)malloc(NPOIN*sizeof(double*)); 

for(int i=0; i<NPOIN; i++)
{
  COORD[i] = (double*)malloc(NDIME*sizeof(double));
}

fin = fopen("coord", "r");
fgets(line, 256, fin);
NPOIN = atoi(line);
char *token;

for(IPOIN=0; IPOIN<NPOIN; IPOIN++)
{
   fgets(line, 256, fin);
   token = strtok(line," \t" );
   COORD[IPOIN][0] = atof(token); //line 891          
   token = strtok(NULL, " \t");
   COORD[IPOIN][1] = atof(token);

}

我编译了代码,一切正常。但是当我运行它时,gdb 在第 891 行显示分段错误。任何人都可以提供一些建议吗?我被卡住了!

4

1 回答 1

5

以下是您使用的调试方式printf
尽管您应该真正学会使用 GDB 或其他调试器单步调试您的代码

fin = fopen("coord", "r");
if (fin == NULL)  printf("failed to open\n");


fgets(line, 256, fin);
printf("Got first line as %s\n", line);

NPOIN = atoi(line);
printf("NPOIN is now %d\n", NPOIN);

char *token;

for(IPOIN=0; IPOIN<NPOIN; IPOIN++){
      fgets(line, 256, fin);
      printf("Got a line as %s\n", line);

      token = strtok(line," \t" );
      printf("Got token #1 %s\n", token);

      COORD[IPOIN][0] = atof(token); //line 891
      printf("Found float %f\n", COORD[IPOIN][0]);

      token = strtok(NULL, " \t");
      printf("Got token #2 %s\n", token);
      COORD[IPOIN][1] = atof(token);
      printf("Found float %f\n", COORD[IPOIN][1]);
}
于 2013-09-17T17:07:48.867 回答