现在的位置: 首页 > 综合 > 正文

指向结构的指针(K&R摘录

2014年01月09日 ⁄ 综合 ⁄ 共 957字 ⁄ 字号 评论关闭

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define MAXWORD 100
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;
}
  
/*binsearch 函数:在tab[0].........tab[n-1]中查找与读入单词匹配的元素*/
struct key *binsearch(char *word,struct key *tab,int n)
{
    int cond;
    struct key *low =&tab[0];
    struct key *high=&tab[0];
    struct key *mid;
    while(low<high)
     {
         mid=low+(high-low)/2;/**************************为什么?**************************/
        /****注意为什么不是mid=(high+low)/2*****************/
        if((cond=strcmp(word,mid->word))<0)
             high=mid;
        else if(cond>0)
             low=mid+1;
        else
            return mid;
     }
    return NULL;
}

抱歉!评论已关闭.