为什么我的指针数组在 C 语言中存在分段错误?



我正在尝试自己实现trie树,通过将字符存储在字符数组中来提交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]='';        //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 initialize next 
//if haven't initialized yet
}
}
}

试试这个,

#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("%sn", 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);
}

相关内容

  • 没有找到相关文章

最新更新