我正在尝试在普通的旧C中实现一个基本的trie结构,并且在编译时我得到一个“节点没有成员”错误。
这是我的结构定义:
typedef struct node {
bool word;
struct node *alpharray[26];
} node;
我尝试初始化某些节点如下:
node *root = malloc(sizeof(node));
node *nptr = malloc(sizeof(node));
nptr = root;
上面的代码使用“iterator”作为指针,它将在创建时循环通过给定的trie结构。这是如何工作的:
while (ch != '\n' && !feof(fp))
{
//get the array index value for the current character (ch)
//getCharNum() returns an int 0-25 corresponding to a slot for a node's alpharray
int char_num = getCharNum(ch);
//if a character has not been put in the given slot yet, make a new node and point
if (nptr->alpharray[char_num] == NULL)
{
node *newnode = malloc(sizeof(node));
nptr->alpharray[char_num] = newnode;
nptr = newnode;
}
//otherwise, move the main pointer to the next node in the chain of nodes
else
{
nptr = nptr->alpharray[char_num];
}
//get the next character
fread(&ch, sizeof(char), 1, fp);
}
每次尝试访问和/或更改任何给定节点属性时,编译重复时出现的错误。我也尝试了* node.alpharray表示法,据我所知,它与上述相同,因为节点将被解除引用。
我知道这可能是我忽视的基本内容,但我似乎无法在任何地方找到解决方案。想法?
这是编译器输出:
gcc -ggdb -std=c99 -Wall -Werror -c -o dictionary.o dictionary.c
dictionary.c:30:15: error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
dictionary.c: In function 'load':
dictionary.c:74:21: error: 'node' has no member named 'alpharray'
dictionary.c:77:21: error: 'node' has no member named 'alpharray'
dictionary.c:84:28: error: 'node' has no member named 'alpharray'
dictionary.c:71:17: error: variable 'char_num' set but not used [-Werror=unused-but-set-variable]
dictionary.c:93:16: error: 'node' has no member named 'word'
cc1: all warnings being treated as errors
make: *** [dictionary.o] Error 1
答案 0 :(得分:1)
您忘记初始化数组中的指针。尝试:
struct node {
bool word;
struct node *alpharray[26];
};
struct node *node_new(void)
{
struct node * ret;
unsigned uu;
ret = malloc (sizeof *ret);
if (!ret) return ret;
ret->word = false;
for (uu = 0; uu < 26 ; uu++) {
ret->alpharray[uu] = NULL;
}
return ret;
}
int main(void)
{
struct node *root , *nptr;
root = node_new();
for (nptr=root; (ch = fgetc( fp)) != EOF; ) {
if (ch == '\n') break;
//get the array index value for the current character (ch)
//getCharNum() returns an int 0-25 corresponding to a slot for a node's alpharray
int char_num = getCharNum(ch);
//if a character has not been put in the given slot yet, make a new node and point
if (nptr->alpharray[char_num] == NULL)
{
nptr->alpharray[char_num] = node_new();
}
nptr = nptr->alpharray[char_num];
}
}
答案 1 :(得分:0)
如果您将节点初始化为:
node *nptr = malloc(sizeof(node));
您为节点本身创建空间,但不为
中的每个指针创建空间struct node *alpharray[26];
由于alpharray将为NULL,因此无法使用它直接获取元素。你也必须为这些元素使用malloc。
答案 2 :(得分:0)
你的'alpharray'应声明为:
struct node** alpharray[26];
因为在行中:
nptr->alpharray[char_num] = newnode;
你要指定一个结构的指针(这是非法的)。 您的节点声明应为:
typedef struct node {
bool word;
struct node** alpharray[26];
} node;
当编译器看到你的(原始)'alpharray'声明时,它无法弄明白 数组中每个元素的大小(因为类型尚未完全定义)。 这就是为什么它不能以任何其他方式工作而不是指针数组(你所做的是'struct node'数组,而不是指向'struct node'的指针数组 - 你应该做什么)。