简体   繁体   English

使用动态 memory 分配将文件中的字符串存储在二维数组中

[英]Store in a two-dimensional array strings from a file using dynamic memory allocation

At the end of this question you will find a piece of code that I am trying to write to read a file called words.txt with the following strings:在这个问题的最后,你会发现我正在尝试编写一段代码来读取一个名为words.txt的文件,其中包含以下字符串:

uno dos tres cuatro cinco seis siete ocho nueve diez

The aim of the code is to be able to store the strings in a two-dimensional array with dynamic memory allocation.该代码的目的是能够将字符串存储在具有动态 memory 分配的二维数组中。 This means it would need to work with any file that has strings.这意味着它需要使用任何具有字符串的文件。

I would need to check:我需要检查:

  • Why the code is not working.为什么代码不起作用。
  • How can I make it so that it stores whatever number of words the file has.我怎样才能让它存储文件中包含的任何数量的单词。

Thank you very much guys!非常感谢你们!

#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;
}
  • You forgot to pass fich to fscanf() .您忘记将fich传递给fscanf() (This is why your code won't work) (这就是您的代码不起作用的原因)
  • Checking if fscanf() is successful should be performed.检查fscanf()是否成功。
  • You can use realloc() for dynamic re-allocation.您可以使用realloc()进行动态重新分配。
  • You should increment i for storeing all strings.您应该增加i以存储所有字符串。
  • Maximum length of string to read should be specified to avoid buffer overrun.应指定要读取的字符串的最大长度以避免缓冲区溢出。

Try this:尝试这个:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM