2017-07-27 42 views
1

我试图让我自己实现一个特里树来提交C中的单词列表,通过在chars数组中存储chars,然后访问下一个节点来存储下一个数组,每个节点包含在但是当我调试它时,似乎与下一个节点数组的连接丢失,因为它表示它为空。为什么我的指针数组在C中有一个分段函数?

这是结构:

typedef struct node { 
    char c[ALLCHAR]; 
    struct node *next[ALLCHAR]; 
} listword; 

listword *head; 
listword *current; 

而这正是实现:

head = malloc(sizeof(listword));  //Initialize the head 
current = head;      //Pass the pointer to current 
dict = fopen(dictionary, "r");   //This is the source of the words 

if(dict==NULL) { 
    fclose(dict); 
    return 1; 
} 
//Here I iterate char by char in the dict 
for(int c=fgetc(dict);c!=EOF;c=fgetc(dict)) 
{ 
    int myc=tolower(c)-97;   //The index equivalent to the char 
    if(c=='\n') { 
      current->c[27]='\0';  //The end of the word 
      current=head;   //Pass the start pointer to the current 
    } else { 
     current->c[myc]=c;   //Here it puts the char in its position 
     current=current->next[myc]; //Here I identify my problem, even 
            //when I already initialized next it 
            //appears as no value 
     if(!current) { 
      current=malloc(sizeof(listword)); //Here I initiliaze next 
               //if haven't initiliazed yet 
     } 
    } 
} 

请帮我在这个问题上,在此先感谢。

+2

现在是学习如何使用调试器来调试你的代码的好时机。一旦你这样做了,并收集了一些相关的细节,请编辑你的问题,并发布你发现的 – OldProgrammer

+0

你确定'0 <= myc yano

+1

该文件是否包含换行符?如果是这样,您将使用''\ n' - 91'作为数组索引 - kaboom!至少在它工作之前,我建议检查数组索引。 –

回答

0

试试这个,

#include <stdio.h>  
#include <stdlib.h> 

typedef struct node { 
    char data[1024]; 
    struct node *next; 
} listword; 

listword *head = NULL; 


// add string to listword 
void add(char *value) { 
    listword *tmp; 

    tmp = (listword*) malloc(sizeof(listword)); 
    if (tmp) { 
     memcpy(tmp, value, sizeof(tmp)); 

     tmp->next = head; 
     head = tmp; 
    } 
}  

// show data of listword 
void show() { 
    listword *tmp; 

    tmp = head; 
    while (tmp) { 
     printf("%s\n", tmp->data);   

     tmp = tmp->next; 
    } 
} 

int main() { 
    FILE * file; 
    char * line = NULL; 
    size_t len = 0; 
    ssize_t buffer; 

    // open 
    file = fopen("dictionary", "r"); 
    if (file == NULL) { 
     exit(1); 
    } 

    // read line of lines of file and add to listword 
    while ((buffer= getline(&line, &len, file)) != -1) { 
     add (line); 
    } 

    // close and free file 
    fclose(file); 
    if (line) { 
     free(line); 
    } 

    // show data 
    show(); 

    return (0); 
} 
相关问题