分段错误和结构变量无法打印到文件

时间:2012-04-24 17:48:21

标签: c struct segmentation-fault

当我尝试在struct to file中打印一些变量时,我收到了分段错误。当我第一次编写代码时,我能够将结果打印到屏幕上,除了最后显示的分段错误

但是,当我更改我的代码以便打印到文件时,它会创建文件,但文件为空,而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;
}

编辑:修复了代码,以便不再显示分段错误。 现在有效。

感谢。

1 个答案:

答案 0 :(得分:1)

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

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

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

for (i=0; i<len ; i++) {
    ...
    artWalker[i]->struct_member;
    ...
}