Interview Questions

I am reading lines from a file into an array ...

C Interview Questions and Answers


(Continued from previous question...)

I am reading lines from a file into an array ...

Q: I'm reading lines from a file into an array, with this code:
char linebuf[80];
char *lines[100];
int i;

for(i = 0; i < 100; i++) {
char *p = fgets(linebuf, 80, fp);
if(p == NULL) break;
lines[i] = p;
}

Why do all the lines end up containing copies of the last line?

A:You have only allocated memory for one line, linebuf. Each time you call fgets, the previous line is overwritten. fgets doesn't do any memory allocation: unless it reaches EOF (or encounters an error), the pointer it returns is the same pointer you handed it as its first argument (in this case, a pointer to your single linebuf array).
To make code like this work, you'll need to allocate memory for each line.

(Continued on next question...)

Other Interview Questions