首页 > 代码库 > 单词计数

单词计数

单词计算程序,为啥遍历输出的时候会出现段错误

  1 #include<stdio.h>  2 #include<ctype.h>  3 #include<string.h>  4 #include<stdlib.h>  5   6 #define MAXWORD 100  7   8 struct tnode{  9     char *word; 10     int count; 11     struct tnode *left; 12     struct tnode *right; 13 }; 14  15 struct tnode *addtree(struct tnode* ,char *); 16 void treeprint(struct tnode*); 17 int getword(char *,int); 18  19 main() 20 { 21     struct tnode *root; 22     char word[MAXWORD]; 23      24     root=NULL; 25     while(getword(word,MAXWORD)!=EOF) 26         if(isalpha(word[0])) 27             root=addtree(root,word); 28      29     treeprint(root); 30      31     printf("%d\n",num); 32      33     getchar(); 34     int m; 35     return 0; 36 } 37  38 struct tnode *talloc() 39 { 40     return (struct tnode *) malloc (sizeof(struct tnode)); 41 } 42   43 struct tnode* addtree(struct tnode *p,char *w) 44 { 45     int cond; 46      47     if(p==NULL) 48     { 49         p=talloc(); 50         p->word=strdup(w); 51         p->count=1; 52         p->left=p->right=NULL; 53     } 54     else if((cond=strcmp(w,p->word))==0) 55         p->count++; 56     else if(cond<0) 57         p->left=addtree(p->left,w); 58     else 59         p->right=addtree(p->right,w); 60          61     return p; 62 } 63  64 void treeprint(struct tnode *p) 65 { 66     if(p!=NULL) 67     { 68         treeprint(p->left); 69         printf("%s %4d\n",p->count,p->word); 70         //num++; 71         treeprint(p->right); 72     } 73          74 } 75  76  77 #define BUFFSIZE 100 78  79     char buf[BUFFSIZE]; 80     int bufp=0; 81 int getch() 82 { 83     return bufp>0 ? buf[--bufp] : getchar(); 84 } 85  86 void ungetch(int c) 87 { 88     if(bufp>BUFFSIZE) 89         printf("ungetch: too many characters\n"); 90     else 91         buf[bufp++]=c; 92 } 93  94 int getword(char *word,int lim) 95 { 96     int c; 97     char *w=word; 98     while(isspace(c = getch())) 99         ;100     if(c!=EOF)101         *w++=c;102     if(!isalpha(c))103     {104         *w=\0;105         return c;106     }107     for(;--lim>0;w++)108         if(!isalnum(*w=getch()))109         {110             ungetch(*w);111             break;112         }113     *w=\0;114     return word[0];115 }