[英]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:我需要检查:
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;
}
fich
to fscanf()
.fich
传递给fscanf()
。 (This is why your code won't work) fscanf()
is successful should be performed.fscanf()
是否成功。realloc()
for dynamic re-allocation.realloc()
进行动态重新分配。i
for storeing all strings.i
以存储所有字符串。 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.