I am trying to write a function that reads a text file and copies each line of the text file into a line of an array that is passed into the function.
void read_lines(FILE* fp, char*** lines, int* num_lines) {
int i = 0, line_count = 0;
char line[256], c;
fscanf(fp, "%c", &c);
while(!feof(fp)){
if(c == '\n') {
++line_count;
}
printf("%c", c);
fscanf(fp, "%c", &c);
}
rewind(fp);
*num_lines = line_count;
lines = (char***)malloc(line_count * sizeof(char**));
while (fgets(line, sizeof(line), fp) != NULL) {
lines[i] = (char**)malloc(strlen(line) * sizeof(char*));
strcpy(*lines[i], line);
}
++i;
}
}
The initial part scans for newlines so that I know how much to allocate to lines initially. I am not sure where I am going wrong.
Additionally, if anybody has any resources that could help me to better understand how to dynamically allocate space, that would be greatly appreciated.
mallocin C. What are the barriers to understanding pointers and what can be done to overcome them?*linesto modify the caller's variable. That's why you have the triple pointer.*lines = malloc((line_count+1) * sizeof(char*));,(*lines)[i] = malloc(strlen(line) +1);,strcpy((*lines)[i], line);