c - K&R 反向抛光计算器中 buf 数组的用途是什么

标签 c arrays char kernighan-and-ritchie

buf 数组永远不会有超过一个元素,因为 getop 的实现。那么,它不能被声明为一个普通的char变量吗?

这是程序的源代码,第 74 - 79 页:

#include <ctype.h>

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

/* getop: get next character or numeric operand */
int getop(char s[]) /* we pass s[] to getop to store input */
{
    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;
}

#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0;
/* getch: the function which actually gets chars! */
int getch(void) /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back in input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

最佳答案

在讨论 getop() 之后的几段中,这本书对 ungetch() 的实现有这样的说法(强调已添加):

The standard library includes a function ungetch that provides one character of pushback; we will discuss it in Chapter 7. We have used an array for the pushback, rather than a single character, to illustrate a more general approach.

关于c - K&R 反向抛光计算器中 buf 数组的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908256/

相关文章:

c - 如何知道何时使用单链表或接地头链表

c - 链表的二维数组

c++ - 如何将 double 转换为整数

c - 拒绝指针的数组大小的宏

c - 数组指针到数组的转换 - C/C++ 初学者

OpenCV:如何从ueye相机将CHAR数据加载到UCHAR cv::Mat结构中

c - 通过 C 中的方法动态分配和填充变量

c++ - C++ 中的矩阵和 vector 模板类

c++ - 将文本文件读入 char 数组。 C++ ifstream

c - 字符串的名称是 char 指针吗?