Q Mallow Q Mallow - 19 days ago 5
C Question

copy a text file to an array

I'm supposed to copy

fp
to lines.
I first find the length of the texts in
fp

then I dynamically allocate lines and retrieve the texts using
fgets
.
I keep getting a "
Your return code was -11 but it was supposed to be 0
" on my auto grader. This is only part of the code of course. I have a makefile and main.
Where is my seg fault??

void read_lines(FILE* fp, char*** lines, int* num_lines){

int num_chars=0;

int index=0;

int lengths[index];

int i=0;

//find the length of the rows n cols in fp

//while there is still character in the text
while(!feof(fp)){
//get that character
char current_char= fgetc(fp);
//implement the number character
num_chars++;

//enter at the end of the first then each line
if(current_char=='\n'){
//find the length of the next line of sentence/word.
// This array stores the length of characters of each line
lengths[index]= num_chars;
//update index
index++;

// Reset the number of characters for next iteration
num_chars = 0;
// Increment the number of lines read so far
(*num_lines)++;
}

}


//now we need to copy the characters in fp to lines
(*lines)=(char**) malloc((*num_lines)*sizeof(char*));
for(i=0;i<*num_lines;i++){
(*lines)[i]=(char*)malloc(lengths[i]*sizeof(char));
fgets(*lines[i],(lengths[i]+1),fp);
fseek(fp,0,SEEK_SET);
}
}

Answer

I'm seeing two problems, here.

First, lengths is statically allocated with zero bytes. That can and will never work. You will need to either create a lengths array with a maximum size (say, 256 line maximum) or make lengths a linked list so that it can grow with the index. Alternatively, you can make two passes through the file - once to get the number of lines (after which you allocate your lines array) and once to get the number of characters per line.

Second, although it is a nitpick, you can greatly simplify the code by removing num_lines from your while loop. After of the loop, just set

*num_lines = index;