Q Mallow Q Mallow - 1 year ago 131
C Question

copy a text file to an array

I'm supposed to copy

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

then I dynamically allocate lines and retrieve the texts using
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
//get that character
char current_char= fgetc(fp);
//implement the number character

//enter at the end of the first then each line
//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

// Reset the number of characters for next iteration
num_chars = 0;
// Increment the number of lines read so far


//now we need to copy the characters in fp to lines
(*lines)=(char**) malloc((*num_lines)*sizeof(char*));

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download