Noxter Noxter - 20 days ago 8
C Question

C - Reading sentences from file into malloc created array of strings

I will be short on what is the problem:

I created an array of strings using malloc.
Now, I want to put sentences from a txt file into these strings.
I do not get any error, but when I want to print out the strings after the "read-in", it is just blank, there are no sentences at all.

I link the code of the program related to this.

Where did I make a mistake?

Please help.

Thanks!

EDIT: I got the problem.

questions[i]=(char*) malloc(sizeof(char));


Is only allocates 1 byte.
The question now is the following: HOW should I allocate more bytes then?
These 'question[i]'s should be as 'long' as the sentence in it, said the teacher, but I do not know how to accomplish that.

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]);
}

Answer

There are three mistakes.

malloc(sizeof(char))

,

fgets(questions[i],sizeof(char),fp);

and sequence of

free(...)


[1]:

int maxLengthOfString = 128; // or more.
...
(char*) malloc(sizeof(char) * maxLengthOfString);

because

sizeof(char) // == just 1 byte == 1 character == only '\0' in string.


[2]:

fgets(questions[i], sizeof(char) * maxLengthOfString, fp);

same reason as [1].


[3]:

for(i=0; i<numbofquestions; i++)
{
    free(questions[i]);
}
free(questions);

free(...) must in reverse order on this situation.

Comments