下面的代码读取一行并返回行长度.lim是数组s []的长度.
当输入行长度为lim时,则s [lim] ='\ 0'.但是数组s []只有长度,从s [0]到s [lim-1].它会导致缓冲区溢出吗?我测试了很多次,但代码似乎工作得很好.
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;
Run Code Online (Sandbox Code Playgroud)
}
c ×2