【问题标题】:How to scan string from file and store it on an array of strings (two-dimensional array)? [duplicate]如何从文件中扫描字符串并将其存储在字符串数组(二维数组)中? [复制]
【发布时间】:2019-02-06 06:43:29
【问题描述】:

我正在扫描文件中的字符串并将其存储到字符串数组中。当我编译我的程序时,它不会产生任何错误,但是当我运行它时,它会显示Segmentation fault (core dumped)。我知道错误在 fscanf 语句中,但我无法弄清楚是什么问题。

我的代码如下所示:

 FILE    *stringsIn = fopen("strings.txt", "rt");
 char    *strings[INPUT_STRINGS];

    for (int i = 0; i < INPUT_STRINGS; i++)
            fscanf(stringsIn, "%s ", &strings[i][0]);

【问题讨论】:

  • 字符串是一个以空字符结尾的字符数组。您的程序中唯一的错误是指针 数组。要使指针在fscanf 等函数中可用,它需要指向某处

标签: c arrays file-handling filehandle


【解决方案1】:

你有一个指针数组,但你没有为每个字符串分配空间。在这种情况下,您可以做的是预先分配一个足够大的缓冲区或在预先分配的缓冲区中读取,查看读取了多少字符并分配该大小的字符串。

FILE    *stringsIn = fopen("strings.txt", "rt");
char    *strings[INPUT_STRINGS];

for (int i = 0; i < INPUT_STRINGS; i++) {
   strings[i] = (char*)malloc(2048); //allocate a big enough buffer
   fscanf(stringsIn, "%2047s ", &strings[i][0]);
}

第二个版本是这样的:

FILE    *stringsIn = fopen("strings.txt", "rt");
char    *strings[INPUT_STRINGS];
char temp[2048];

for (int i = 0; i < INPUT_STRINGS; i++) {
   fscanf(stringsIn, "%2047s ", &temp);
   size_t len = strlen(temp);
   strings[i] = (char*)malloc(len + 1);
   strncpy(strings[i], temp, len);
}

【讨论】:

  • 永远不要使用"%s"而不指定宽度来限制要读取的字符数。 malloc(len) 一个一个。
  • "strncpy(strings[i], temp, len);":为什么不只是strcpy(strings[i], temp)?! strnpcy() 的用法很容易出错,你应该很容易就站稳脚跟,不幸的是你展示的代码证明了这一点。
  • 另外:不要将malloc()和朋友的结果投射到C中。
  • 我不明白为什么在 malloc 之前有一个 (char *)。你能解释一下吗?
  • cplusplus.com/reference/cstdlib/malloc 在文档中说 malloc 返回 void*,所以我将结果转换为 char*。我认为一些较新的编译器不需要它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多