Search code examples
cfilefgetsrealloc

Re: Reading a line and using realloc in C


So I browsed some of the same questions and found a working answer. I was just wondering if someone can explain to me the last line of the code from this answer:

Read text from a file and realloc when needed

fgets(linebuffer + (maxlinelen/2 - 1), maxlinelen/2 + 1, fp); //this line

Thank you very much!


Solution

  • The writer is trying to read into the second half of the array. In order to do that, the base address must be higher. Hence the first argument linebuffer + (maxlinelen/2 - 1). It's taking the base address of the array, and adding half the array's length to it.

    But since the array is half as long, the writer halves the size of the array. Hence the second argument, maxlinelen/2 + 1.

    enter image description here