C,keytab程序

时间:2016-01-06 10:55:22

标签: c structure

我正在尝试用K& R从C lang运行一个c程序。 (第6.1章6.1练习前)

这是代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define BUFSIZE 100

#define MAXWORD 100
#define NKEYS (sizeof keytab)

struct key {
    char *word;
    int count;
    } keytab[] = {
        "auto", 0,
        "break", 0,
        "case", 0,
        "char", 0,
        "const", 0,
        "continue", 0,
        "default", 0,
        "unsigned", 0,
        "void", 0,
        "volatile", 0,
        "while", 0
    };



char buf[BUFSIZE];
int bufp = 0;
int getch(void);
void ungetch(int);


int getword(char *, int);
struct key *binsearch(char *, struct key *, int);



main()
{


    char word[MAXWORD];
    struct key *p;
    while (getword(word, MAXWORD) != EOF)
        if (isalpha(word[0]))           
        if ((p=binsearch(word, keytab, NKEYS)) != NULL)
            p->count++;
        for (p = keytab; p < keytab + NKEYS; p++)
            if (p->count > 0)
                printf("%4d %s\n", p->count, p->word);
        return 0;
}

struct key *binsearch(char *word, struct key *tab, int n)
{
    int cond;
    struct key *low = &tab[0];
    struct key *high = &tab[n];
    struct key *mid;


    while (low < high) {
        mid = low + (high-low) / 2;
        if ((cond = strcmp(word, mid->word)) < 0)
            high = mid;
        else if (cond > 0)
            low = mid + 1;
        else
            return mid;
    }
    return NULL;
}


int getword(char *word, int lim)
{

    int c, getch(void);
    void ungetch(int);
    char *w = word;

    while (isspace(c = getch()))
        ;
    if (c != EOF)
        *w++ = c;
    if (!isalpha(c)) {
        *w = '\0';
        return c;
    }
    for ( ; --lim > 0; w++)
        if (!isalnum(*w = getch())) {
            ungetch(*w);
            break;
        }
    *w = '\0';
    return word[0];
}


int getch(void)
{
      return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)
{ 
      if (bufp >= BUFSIZE)
         printf("ungetch: too many characters\n");
      else 
         buf[bufp++] = c;
}

我已经检查了10次代码我找不到任何错误。我确实理解代码应该如何工作的逻辑。我正在使用ubuntu 15.04,我通过终端编译代码。

1 个答案:

答案 0 :(得分:1)

问题是NKEYS宏。这应该是数组中的条目数,但它被定义为字节数。只需将其更改为:

#define NKEYS (sizeof(keytab) / sizeof(keytab[0]))

解决问题所需的一切。