【发布时间】:2018-01-03 16:56:07
【问题描述】:
我正在尝试通过将字符存储在字符数组中,然后访问下一个节点以存储下一个数组,从而在 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 initialize next
//if haven't initialized yet
}
}
}
【问题讨论】:
-
现在是学习如何使用调试器调试代码的好时机。完成此操作并收集一些相关详细信息后,请编辑您的问题并发布您发现的内容
-
你确定
0 <= myc < ALLCHAR总是正确的吗? -
文件是否包含换行符?如果是这样,您将使用
'\n' - 91作为数组索引 - kaboom!至少在它工作之前,我建议检查数组索引。 -
你没有在 head->next 中初始化任何东西。该数组包含垃圾数据。
current = current->next[myc]将随机数据分配给current。 -
如果文件无法打开,
if (dict==NULL) fclose(dict)肯定会导致崩溃。
标签: c arrays segmentation-fault trie