K&R 中的 getline 函数定义

Dia*_*orp 2 c for-loop c-strings getchar

以下是第 29 页 K&R 中的 getline 实现,

# define MAXLINE 1000
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)

我不明白为什么我们需要在 for 循环中执行“i < lim - 1”。对于正确的索引,为什么“ i < lim ”不够?

任何帮助将非常感激...

Vla*_*cow 5

该函数将构建一个字符串(存储在参数指定的数组中char s[]),该字符串是一个以零终止字符结尾的字符序列'\0'

因此,数组的一个元素被保留用于在退出函数之前附加到字符数组的终止零字符

s[i] = '\0';
Run Code Online (Sandbox Code Playgroud)

例如,如果变量lim等于,5那么您可以在数组中输入不超过4索引范围内的字符[0, 3]。在这种情况下(如果所有字符都将被填充)在数组的最后一个元素中,将在位置 处lim-1写入终止零字符。'\0'4