6.4 Pointers to structures
#include <stdio.h>#include<ctype.h>#include<string.h>#defineMaxword 100//int Binsearch (char *, struct key *, int);#defineNkeys (sizeof keytab/sizeof (keytab[0]))#defineBUFSIZE 100intGetword (Char*,int);CharBuf[bufsize];intBUFP =0;structKey {Char*Word; intcount;} Keytab[]= { "Auto",0, " Break",0, " Case",0, "Char",0, "Const",0, "Continue",0, "default",0, /* ... */ "unsigned",0, "void",0, "volatile",0, " while",0};/*Count C Keywords*/Main () {intN; CharWord[maxword]; while(Getword (Word, maxword)! =EOF)if(Isalpha (word[0])) if((n = binsearch (Word, keytab, Nkeys)) >=0) Keytab[n].count++; for(n =0; n < Nkeys; n++) if(Keytab[n].count >0) printf ("%4d%s\n", Keytab[n].count, Keytab[n].word); return 0;}/*binsearch:find Word in tab[0]...tab[n-1]*/intBinsearch (Char*word,structKey tab[],intN) { intcond; intLow , high, mid; Low=0; High= N-1; while(Low <=High ) {Mid= (Low+high)/2; if((cond = strcmp (Word, Tab[mid].word)) <0) High= Mid-1; Else if(Cond >0) Low= Mid +1; Else returnmid; } return-1;}/*Getword:get Next word or character from input*/intGetword (Char*word,intLim) { intC, Getch (void); voidUngetch (int); Char*w =Word; while(Isspace (c =getch ())) ; if(c! =EOF)*w++ =C; if(!Isalpha (c)) { *w =' /'; returnC; } for(;--lim >0; w++) if(!isalnum (*w =getch ())) {Ungetch (*W); Break; } *w =' /'; returnword[0];}intGetch (void)/*get A (possibly pushed-back) character*/{ return(Bufp >0) ? buf[--BUFP]: GetChar ();}voidUngetch (intC/*push character back on input*/{ if(BUFP >=BUFSIZE) printf ("Ungetch:too many characters\n"); ElseBUF[BUFP++] =C;}
The terminal output shows:
Da
Gfa
Ray
Allen
Auto
void
Los
Static
Register
Break
Ls
Case
void
Auto
Break
Continue
2 Auto
2 break
1 case
1 continue
2 void
Sixth chapter Structure