I have tried several solutions from other sites, but none of them worked. It always gives this "segmentation fault" message. please tell me what's wrong. thanks in advance!
Code:
#include <stdio.h>
#include <stdlib.h>
struct tnode {
char *word;
int count;
struct tnode *left;
struct tnode *right;
};
struct tnode *addtree ( struct tnode *p, char *w );
struct tnode *talloc ( void );
int strcmp ( char *t, char *s );
void cpword ( char *from, char *to );
void treeprint ( struct tnode *p );
char getword ( char *word );
int main ( void )
{
char word [20];
struct tnode *root;
printf ( "enter the text below:\n\n" );
while ( ( getword ( word ) ) != EOF )
if ( isalpha ( word ) )
addtree ( root, word );
printf ( "\n%-20s: %s\n\n", "word", "count" );
treeprint ( root );
return 0;
}
struct tnode *addtree ( struct tnode *p, char *w )
{
int temp;
if ( p == NULL ) {
p = talloc ();
cpword ( w, p->word );
p->left = NULL;
p->right = NULL;
p->count = 0;
}
else if ( ( temp = strcmp ( w, p->word ) ) == 0 )
++p->count;
else if ( temp < 0 )
p->left = addtree ( p->left, w );
else
p->right = addtree ( p->right, w );
return p;
}
struct tnode *talloc ( void )
{
return ( ( struct tnode * ) malloc ( sizeof ( struct tnode ) ) );
}
int strcmp ( char *t, char *s )
{
while ( *t && *s ) {
if ( *t == *s ) {
t++;
s++;
}
else
return ( *t - *s );
}
return 0;
}
void cpword ( char *from, char *to )
{
while ( *from )
*( to++ ) = *( from++ );
*to = '\0';
}
void treeprint ( struct tnode *p )
{
if ( p != NULL ) {
treeprint ( p->left );
printf ( "%-20s: %d\n", p->word, p->count );
treeprint ( p->right );
}
}
char getword ( char *word )
{
char temp;
char *w = word;
while ( !isalnum ( temp = getchar () ) )
;
while ( isalnum ( temp ) ) {
*w++ = temp;
temp = getchar ();
}
*w = '\0';
return *word;
}