Im 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?
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. See question 20.2 for an example. References: K&R1 Sec. 7.8 p. 155 K&R2 Sec. 7.7 pp. 164-5 ISO Sec. 7.9.7.2 H&S Sec. 15.7 p. 356 comp.lang.c FAQ list ยท Question 7.5a Q: I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage. A: Whenever a function returns a pointer, make sure that the pointed-to memory is properly allocated. For example, make sure you have not done something like #include
Related Questions
- Im 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?
- How can I create a C++ function f(int,char,float) that is callable by my C code?
- How can I call a non-system C function f(int,char,float) from my C++ code?