getop()中的澄清

Thu*_*nch 4 c kernighan-and-ritchie

在Dennis Ritchie的"C编程语言"一书中,在getopop函数中,他声明s [1] ='\ 0'为什么他会在索引1上结束数组?有什么意义和需要?

在后面的部分,他确实使用了数组的其他部分..

int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';

    if (!isdigit(c) && c != '.')
        return c; /* not a number */

    i = 0;
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()))
            ;

    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';

    if (c != EOF)
        ungetch(c);

    return NUMBER;
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 8

因为函数可能在读取剩余输入之前返回,然后s需要是一个完整(和终止)的字符串.