Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

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?

array char code file int Reading
0
10 Posted

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?

0
10

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 char *itoa(int n) { char retbuf[20]; /* WRONG */ sprintf(retbuf, “%d”, n); return retbuf; /* WRONG */ } When a function

Related Questions

Experts123