I'm having a difficult time understanding this function:
int getline(char s[], int lim)
{
int c,i;
for (i=0; i<lim-1 && (c=getchar()) != EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
I will try to explain my doubts with an example input of 0123456789\n
(for a total of 11 characters).
In this example lim=10
and s[]
is set to line[10]
(from the declaration of the calling argument of getline
).
When the loop has finished running trhough ++i
these are the values: i==9
, s[0]==0, ..., s[9]==9
, c=='\n'
(because getchar
executes as part of the check condition).
Then the if
checks positive and s[9]
is set to '\n'
while i
is raised to 10
.
Finally, s[10]
is set to '\0'
, but s[10]
doesn't exist!
Also, s[]
later prints to 012345678
with the value of s[9]
being reserved for one between '\n'
and '\0'
.
Where is '\0'
being stored? I know it's there somewhere because later another function makes use of it to check for the end of the array.
Because of the chcek i<lim-1
, if lim
is 10, i
will never become 9
inside for
loop, it can reach a max value of 8
, before the condition check fails.
After i
becomes 9
, the first part of the for
loop condition check fails, and the control comes out of loop [without executing getchar()
for that iteration).
So, upto s[8]
is read and at s[9]
, the \0
is stored.