【问题标题】:Store in a two-dimensional array strings from a file using dynamic memory allocation使用动态内存分配将文件中的字符串存储在二维数组中
【发布时间】:2020-10-12 17:44:40
【问题描述】:

在这个问题的最后,你会发现我正在尝试编写一段代码来读取一个名为 words.txt 的文件,其中包含以下字符串:

uno dos tres cuatro cinco seis siete ocho nueve diez

代码的目的是能够将字符串存储在具有动态内存分配的二维数组中。这意味着它需要处理任何包含字符串的文件。

我需要检查:

  • 为什么代码不起作用。
  • 我怎样才能让它存储文件中包含的任何数量的单词。

非常感谢你们!

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>

int main()
{

char c, *mystring[20];
int i = 0;
FILE *fich;

setlocale(LC_CTYPE,"spanish");
identifica();
    
fich = fopen("words.txt", "r");

do
{
    mystring[i] = malloc (20 * sizeof(char));
    fscanf("%s", mystring[i]);
    printf ("%s", mystring[i]);
}
while ((c=fgetc(fich))!=EOF);

return 0;
}

【问题讨论】:

标签: c string multidimensional-array dynamic


【解决方案1】:
  • 您忘记将fich 传递给fscanf()。 (这就是您的代码不起作用的原因)
  • 应该检查fscanf()是否成功。
  • 您可以使用realloc() 进行动态重新分配。
  • 您应该增加 i 以存储所有字符串。
  • 应指定要读取的字符串的最大长度以避免缓冲区溢出。

试试这个:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>

int main()
{

    char **mystring = NULL;
    int i = 0;
    FILE *fich;

    setlocale(LC_CTYPE,"spanish");
    identifica();
        
    fich = fopen("words.txt", "r");

    for (;;)
    {
        char* next = malloc (20 * sizeof(char));
        if (fscanf(fich, "%19s", next) == 1)
        {
            printf ("%s", next);
            mystring = realloc(mystring, sizeof(*mystring) * (i + 1));
            mystring[i] = next;
            i++;
        }
        else
        {
            free(next);
            break;
        }
    }

    return 0;
}

【讨论】:

  • 善用sizeof(*mystring)。推荐在next = malloc (20 * sizeof(char))类似使用next = malloc(sizeof *next * 20)
  • next = malloc (20 * sizeof(char)) 可以只是 next = malloc (20),因为根据规范,sizeof(char) 必须为 1。
  • 这个学习者代码的 malloc (20) 是正确的。编码malloc(sizeof *next * 20) 确实减少了代码维护,因为以后的代码可能会演变为whar_t *
  • 非常感谢@MikeCAT! :-) 只是几个问题:for (;;) 的含义是什么?另外,为什么你使用这样的 malloc:char* next = malloc (20 * sizeof(char)); 而不是这样的:next = (char*) malloc (20 * sizeof(char));?谢谢!!
  • for (;;) 表示无限循环(直到被breakreturn 等打破)。对于第二个问题,请阅读:c - Do I cast the result of malloc? - Stack Overflow
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多