如何将trie中的所有children设置为NULL

How to set all the children to NULL in the trie

我正在尝试在 C 中实现一个 trie。我的代码编译正确,但是当我 运行 使用 valgrind 时它显示错误。这是有问题的部分:

typedef struct node {
bool end;
struct node *chil[26];
} NODE;
int main()
{
   NODE* ne = (NODE*)malloc(sizeof(NODE)); 
   if(ne->chil[1] == NULL) printf("\nzwycięstwo!\n"); 
   free(ne);
   return 0;
}

这是错误报告:

==3346== Conditional jump or move depends on uninitialised value(s)

==3346== at 0x40076B: main (exp.c:21)

==3346== Uninitialised value was created by a heap allocation

==3346== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64->linux.so)

==3346== by 0x40075A: main (exp.c:20)`

我想我必须明确地说

ne->chill = {NULL};

但这会导致编译器错误 “预期表达”

我该怎么办?我可以避免通过整个数组将指针设置为 NULL 吗?

循环是将所有指针可移植地设置为 NULL 值的唯一方法

for (int i = 0; i < 26; ++i)
  ne->chil[i] = NULL;

您可能会听到使用 callocmemset 的建议。但是零位模式不一定与指针的 N​​ULL 值相同。即使许多平台都是这样实现的。