【问题标题】:K&R What's the purpose of the buf array in reverse polish calculatorK&R 逆抛光计算器中buf数组的作用是什么
【发布时间】:2014-01-03 16:28:59
【问题描述】:

由于 getop 的实现,buf 数组永远不会有多个元素。那么,不能将其声明为普通的 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 中的声明 while ((s[0] = c = getch()) 将暗示 buf 可能包含多个字符。这无法从显示的有限代码示例中确定。如果确实只有一个字符被放入buf,那么,当然,你只需要一个char。但我怀疑你误解了其余的代码。
  • ungetchar() 在 getop 中只使用一次,因此每次函数调用只能上传到缓冲区一个字符。
  • 这只是ungetchar 在特定情况下使用。缓冲区也可以从其他地方加载,在您显示的任何代码中都没有显示。我怀疑uncgetch 是通常加载缓冲区的机制。它更像是一个实用功能来“撤消”先前的getch。您需要查看第 74-79 页上的所有代码,并查看buf 的使用位置。
  • 这里是完整的源代码:pastebin.com/jXGp0aKx,看来buf只在getch和ungetch内部使用。
  • 谢谢。 ungetchgetop 的末尾附近被调用。是否有可能在调用getch 之前多次调用它?

标签: c arrays char kernighan-and-ritchie


【解决方案1】:

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

标准库包含一个函数ungetch,它提供一个回退字符;我们将在第 7 章讨论它。我们使用数组而不是单个字符来表示更通用的方法。

【讨论】:

    【解决方案2】:

    BUFSIZE 可能是 1,如果 getop()only 调用 ungetch() 的函数。

    根据这篇文章,更高级别的代码可能在调用getop()之前已经多次调用ungetch(),因此将多个char填充到buf中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2021-06-21
      相关资源
      最近更新 更多