I found this code in The C Answer Book.
int readline(char s[], int lim) {
int i,c,j=0;
for(i=0; (c=getchar())!=EOF && c!='\n'; ++i) {
if(i<lim-2) {
s[j]=c;
++j;
}
}
if(c=='\n') {
s[j]=c;
++j;
++i;
}
s[j]='\0';
return i;
}
I wrote my version :
int readline(char line[], int lim) {
int c, i;
for(i=0; (c=getchar())!=EOF && c!='\n'; ++i) {
if(i<lim-2) {
line[i]=c;
}
}
if(c=='\n') {
line[i]=c;
++i;
}
line[i]='\0';
return i;
}
I have used only one variable ‘i‘ as counter but the original version has used two variable ‘i‘ and ‘j‘ as counters.
What is the difference between the two?
Please tell me how do they differ?
The second version of the function leaves part of
lineuninitialised and risks writing the final ‘\n’, ‘\0’ beyond the end of thelinebuffer in cases where the initial loop continues beyondi<lim-2