I was trying to improve one of the programs from ANSI C (Kernighan's book) but I have encountered a very annoying problem and can't find out what's wrong. The idea of the program is to count words in a file in such a way:
==file example:==
Hey teacher leave leave the kids alone alone
==result:==
alone - 2
hey - 2
leave - 2
kids - 1
teacher -1
the -1
The program bases on "binary tree" method but I was trying to create an array of ** to every node. But I cannot figure why it doesn't work. Here's the code
Martin
==file example:==
Hey teacher leave leave the kids alone alone
==result:==
alone - 2
hey - 2
leave - 2
kids - 1
teacher -1
the -1
The program bases on "binary tree" method but I was trying to create an array of ** to every node. But I cannot figure why it doesn't work. Here's the code
Code:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
struct tnode{
char *word;
int count;
struct tnode *left;
struct tnode *right;
}***fruits=NULL;
int tcurrsize=0;
void print(void)
{
int i;
for(i=0;i<tcurrsize;i++)
printf("%s\n",((**(fruits[i])).word));
printf("==========\n");
}
void localizeNewFruit(struct tnode** newFruit){
struct tnode ***tmpfruits;
tmpfruits=realloc(fruits,tcurrsize*sizeof(struct tnode **));
if(tmpfruits)
fruits=tmpfruits;
else{
perror("Memmory error");
free(fruits);
exit(1);
}
fruits[tcurrsize-1]=newFruit;
}
struct tnode* addtree(struct tnode *p, char *w){
int cond;
struct tnode **new;
if(p==NULL){
if((p=malloc(sizeof(struct tnode)))!=NULL);
else{
perror("M E");
}
p->word=w;
p->count=1;
p->left=p->right=NULL;
new=&p;
++tcurrsize;
localizeNewFruit(new);
}
else if((cond=strcmp(w,p->word))==0){
p->count++;
free(w);
}
else if(cond<0)
p->left=addtree(p->left,w);
else if(cond>0)
p->right=addtree(p->right,w);
return p;
}
char* getword (FILE* infile){
char *word = NULL, *tmpword, ch;
size_t currsize=1, currpos=0;
while ( (ch=fgetc(infile))!=EOF && (isalpha(ch)) ){
if (currpos>=currsize-1){
currsize *=2;
tmpword=realloc(word, currsize);
if (tmpword)
word=tmpword;
else{
perror("Memory problem");
free(word);
return NULL;
}
}
word[currpos++]=ch;
}
if (currpos){
word[currpos]='\0';
return word;
}
else if (isprint(ch) || iscntrl(ch))
return strdup (" ");
else
return NULL;
}
int main(int argc, char *argv[])
{
char * word;
FILE * infile;
struct tnode *newNode=NULL;
int i;
if (argc!=2){
printf ("Argument error \n");
return 1;
}
infile=fopen(argv[1],"r");
if (!infile){
perror("File error");
exit(1);
}
while ((word=getword(infile))!=NULL){
if (!(strcmp(" ",word)))
free(word);
else{
newNode=addtree(newNode,word);
}
}
print(); /*receive Segmentation fault*/
fclose(infile);
return 0;
}
Martin