此代码工作正常含1000个字的文本文件,但是当我用10000点的话,它会停止响应。
同时,会在main.c用10000个字的作品,当我使用动态数组,而不是二进制树。 所以我认为这个问题是在tree.c码的地方...
tree.h中
#ifndef TREE_H_
#define TREE_H_
typedef struct Item{
char* key;
int no;
} TItem;
typedef struct No{
TItem item;
struct No* pLeft;
struct No* pRight;
} TNo;
void TTree_Insert (TNo**, char[]);
void TTree_Print (TNo*);
#endif
tree.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"
TNo* TNo_Create (char* c){
TNo* pNo = malloc(sizeof(TNo));
pNo->item.key = malloc(sizeof(char)*strlen(c));
strcpy(pNo->item.key, c);
pNo->item.no = 1;
pNo->pLeft = NULL;
pNo->pRight = NULL;
return pNo;
}
void TTree_Insert (TNo** pRoot, char word[80]){
char* c = malloc(sizeof(char)*strlen(word));
strcpy(c, word);
TNo** pAux;
pAux = pRoot;
while (*pAux != NULL){
if (strcmp(c, (*pAux)->item.key) < 0) pAux = &((*pAux)->pLeft);
else if (strcmp(c, (*pAux)->item.key) > 0) pAux = &((*pAux)->pRight);
else{
(*pAux)->item.no++;
return;
}
}
*pAux = TNo_Create(c);
return;
}
void TTree_Print (TNo *p){
if (p == NULL) return;
TTree_Print (p->pLeft);
printf("%s - %d", p->item.key, p->item.no);
TTree_Print (p->pRight);
}
main.c中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "tree.h"
int main(){
TNo* pRoot = NULL;
FILE* txt = fopen("Loremipsum.txt", "r");
char aux[80];
int c, x = 0;
while ((c = fgetc(txt)) != EOF){
while (!(isalpha((char)c))) c = fgetc(txt);
while (isalpha((char)c)) {
if (isupper((char)c)) c = c+32;
if (islower((char)c)) aux[x++] = (char)c;
c = fgetc(txt);
}
aux[x] = '\0';
TTree_Insert(&pRoot, aux);
x = 0;
aux[0] = '\0';
}
TTree_Print(pRoot);
fclose(txt);
return 0;
}