Hi to all!
I have this function that, provided with a target array of strings and a file name, reads it line by line and stores the lines into the given array
Code:
void file_to_array(char **target_lines, char *file_name)
{
FILE *f;
char line[LINE_SIZE];
int num_righe = 0;
f = fopen(file_name, "r");
/* crea il file se non lo trova */
if(f == NULL) {
f = fopen(file_name, "w");
}
while(fgets(line, LINE_SIZE, f)) {
num_righe++;
target_lines = (char**)realloc(target_lines, (sizeof(char*)*num_righe));
target_lines[num_righe-1] = strdup(line);
}
fclose(f);
}
Calling it like follows it gives me a Segmentation fault in the line where I try to print the second item.
Code:
char **lines = NULL;
file_to_array(lines, "spese.dat");
printf("%s", lines[0]);
The file is correct and outputting like by line within the function ( printf("%s", target_lines[num_righe-1]) ) gives the correct lines.
Any help?
Thanks in advance