【发布时间】:2014-10-08 18:37:37
【问题描述】:
这个函数应该将字典加载到 trie 中。我想知道字典文件有多大,这样我就可以同时calloc 所有内存。这样做的原因是所有的内存都可以靠近在一起,因此可以利用有助于加快搜索速度的硬件。我也找到了 2 种方法的建议。其中之一是使用sys/stat.h,您将在我的代码中看到。
当我运行此代码时,我收到一个“分段错误”,我知道这意味着我正在尝试访问我没有权限的内存。通过使用 GDB,我发现分段错误发生在第 116 行(又名:读取“else if (cur->children[key] == NULL)”的行)我发现键中的值在那时间是 12 点。起初我认为问题在于我使用了 calloc 或 sys/stat.h,因为这是我最不了解的两件事。然而,我研究得越多,这似乎就越不可能。如果它不是其中之一,那么我什至不知道该往哪里看。
以下只是我认为相关的代码:
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <sys/stat.h>
#include "dictionary.h"
typedef struct node
{
bool end[26];
struct node* children[26];
} node;
node* start;
int key;
int last;
int dic_count;
bool load(const char* dictionary)
{
struct stat s;
stat(dictionary, &s);
int size = s.st_size;
dic_count = 0;
int z = 1;
FILE* dic = fopen(dictionary, "r");
if (dic == NULL)
{
return false;
}
start = calloc(size, sizeof(node));
if (start == NULL)
{
return false;
}
int l = 0;
int d;
node* cur = &start[0];
while (0 != (d = fgetc(dic)))
{
int d = fgetc(dic);
if (l > 0)
{
last = key;
}
l = 1;
key = d - 'a';
if (d == '\n')
{
cur->end[last] = true;
cur = &start[0];
dic_count++;
}
else if (cur->children[key] == NULL)
{
node* new = &start[z];
cur->children[key] = new;
z++;
if (cur->children[key] == NULL)
{
return false;
}
cur = cur->children[key];
}
else
{
cur = cur->children[key];
}
}
return true;
}
非常感谢任何帮助。
【问题讨论】:
-
什么是
start指向整个所有这些代码? 一个动态节点 ?我认为你需要的不止这些。 -
起始点位于被调用内存中的第一个动态节点。其他节点在该内存中创建。 start 只是起点,而不是整个存储。
-
我不确定文件大小是否能很好地估计您需要的节点数。当您阅读时,您将换行符与其他字符区分开来,您认为这些字符是小写字母。这对我来说似乎很容易出错。
标签: c dictionary dynamic-arrays trie calloc