1

当我尝试将结构中的一些变量打印到文件时,我收到了分段错误。当我第一次编写代码时,我能够很好地将结果打印到屏幕上,除了最后出现的分段错误

但是,当我更改代码以便打印到文件时,它会创建文件,但文件是空的,而是segmentation fault打印到屏幕上。

有什么建议吗?

/* all is an array of struct CASE, 
   artall is an array of struct ARTCOUNT, 
   pLast is last element in all */

void printArtCount (CASE* all, ARTCOUNT* artAll, CASE* pLast)
{
  ARTCOUNT* artWalker = artAll;
  CASE* walker;
  char input[51];
  FILE* spOut;

  printf("File name for artist count output: ");
  scanf("%50s", input);
  spOut = fopen(input, "w");

  while(artWalker->name)
  {
    fprintf(spOut, "%d ", artWalker->count);
    fprintf(spOut, "%s\n", artWalker->name);
    for(walker = all; walker <= pLast; walker++)
    {
       if (strcmp(walker->name, artWalker->name) == 0)
         fputs(walker->art, spOut);
    }
   artWalker++;
  } 

 return;
}

编辑:修复了代码,使分段错误不再出现。现在一切正常。

谢谢。

4

1 回答 1

1

您可能正在读取超出其限制的数组。

请尝试以下循环遍历数组元素的方式。

len = sizeof(artWalker)/sizeof(artWalker[0]);

for (i=0; i<len ; i++) {
    ...
    artWalker[i]->struct_member;
    ...
}
于 2012-04-24T18:01:47.853 回答