我会简短地说明问题是什么:
我使用 malloc 创建了一个字符串数组。 现在,我想将 txt 文件中的句子放入这些字符串中。 我没有收到任何错误,但是当我想打印“读入”后的字符串时,它只是空白,根本没有句子。
我链接了与此相关的程序的代码。
我哪里出错了?
请帮忙。
谢谢!
编辑:我遇到了问题。
questions[i]=(char*) malloc(sizeof(char));
仅分配1个字节。 现在的问题是:我应该如何分配更多字节? 老师说,这些“问题[i]”应该和其中的句子一样“长”,但我不知道如何做到这一点。
char** questions
int numbofquestions=40;
questions=(char**) malloc(sizeof(char*)*numbofquestions);
int i;
for(i=0;i<numbofquestions;i++)
{
questions[i]=(char*) malloc(sizeof(char));
}
FILE* fp;
fp=fopen("sentences.txt", "r");
for(i=0;i<4;i++) // LESS THAN 4 BECAUSE IT IS JUST A TEST, THERE IS ONLY 4 SENTENCES IN THE FILE AT THE MOMENT. EACH SENTENCE IS IN A DIFFERENT ROW.
{
fgets(questions[i],sizeof(char),fp);
printf("%s\n", questions[i]);
}
fclose(fp);
free(questions);
for(i=0;i<numbofquestions;i++)
{
free(questions[i]);
}
最佳答案
存在三个错误。
malloc(sizeof(char))
,
fgets(questions[i],sizeof(char),fp);
和顺序
free(...)
[1]:
int maxLengthOfString = 128; // or more.
...
(char*) malloc(sizeof(char) * maxLengthOfString);
因为
sizeof(char) // == just 1 byte == 1 character == only '\0' in string.
[2]:
fgets(questions[i], sizeof(char) * maxLengthOfString, fp);
与[1]相同的原因。
[3]:
for(i=0; i<numbofquestions; i++)
{
free(questions[i]);
}
free(questions);
在这种情况下,free(...) 必须以相反的顺序。
关于C - 从文件中读取句子到 malloc 创建的字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40612187/