【问题标题】:Segmentation fault whilst reading strings from a text file into a struct将文本文件中的字符串读入结构时出现分段错误
【发布时间】:2015-02-15 09:12:15
【问题描述】:

我试图将一个文件读入一个包含 char 数组的结构,如下面的代码所示,但是它给出了分段错误的输出:11. 我已经尝试了所有方法,包括使用类似的示例,但它已经完成了我的头脑.

我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 1024

struct Raw_Word{
    char word[MAX_LENGTH];
    char filename [25];
    int length;
};

struct Final_Word{
    char word[MAX_LENGTH];
    int length;
    int amount;
};

struct Raw_Word raw_word[MAX_LENGTH];

int main(int argc, char* argv[]) {
if (argc > 10) {
        printf("Maximum of 10 files allowed");
        return 1;
    }

    int i = 0;
    int lines = 0;


    for (i = 1; i <= argc; i++) {
        FILE *fp = fopen(argv[i], "r");
while(fgets(raw_word[lines].word, MAX_LENGTH, fp)){
            //printf("%s", raw_word[lines].word);
        }
        fclose(fp);

    }

    for(int j = 0; j < lines; j++){
        printf("%s\n", raw_word[j].word);
    }

return 0;
}

【问题讨论】:

  • 作为一般说明,查找此类内容的最佳方法之一是首先找出导致错误的行。这可以通过输入打印语句或gdb来完成。

标签: c arrays string struct


【解决方案1】:

线

for (i = 1; i <= argc; i++) 

不对。您需要在argc-1 处停止索引。

for (i = 1; i < argc; i++) 

for (i = 1; i != argc; i++) 

【讨论】:

  • 另外,在与fgets 或任何其他功能一起使用之前检查fp != NULL
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
相关资源
最近更新 更多