用C语言读取文章中的单词(假设不在行中分开,暂时不转换大小写),并将其保存在二叉树中,想着顺了几遍感觉没有什么问题了,结果直接是跳出异常,不知道出了什么问题?竟然连第一个也没插入,实在搞不懂
#include <stdio.h>
#include <stdlib.h>
typedef struct words
{
char word[15];
int n;
} item;
item * node;
typedef struct nodes
{
item gather;
struct nodes * left;
struct nodes * right;
} Node;
void readfile(FILE * fp, Node *);
int main()
{
FILE *fp;
fp = fopen("try.txt", "r");
Node *root;
root = NULL;
readfile(fp, root);
printf("%s", root->gather.word);
return 0;
}
void readfile(FILE * fp, Node * root)
{
char ch;
char cht;
Node *test;
int ss = 0;
while (!feof(fp))
{
ss++;
test = root;
ch = getc(fp);
while (test != NULL )
{
FILE *helper = fp;
int n = 1;
if ((test->gather).word[0] == ch)
while ((cht = getc(helper)) != '\n' && (cht ) != ' ')
{
if ((test->gather).word[n] == cht)
{
n++;
continue;
}
else
break;
}
if ((cht ) == '\n' && (cht) == ' ' && (test->gather).word[n] == cht)
{
test->gather.n++;
fp = helper;
}
else if ((ch < (test->gather).word[0]))
test = test->left;
else
test = test->right;
}
if (test == NULL)
{
test = (Node *)malloc(sizeof(Node));
((test->gather).word[0]) = '\0';
((test->gather)).n = 0;
test->left = test->right = NULL;
}
if (test->gather.word[0] == '\0')
{
test->gather.word[0] = ch;
test->gather.n++;
int x = 1;
while ((ch = getc(fp)) != '\0' && (ch) != ' ')
{
test->gather.word[x] = ch;
x++;
}
test->gather.word[x] = '\0';
}
}
}
root使用时一直是空指针,所以异常,需要先分配空间