Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';我不懂C语言_C_Debugging_Pointers_Trie_Cs50 - Fatal编程技术网

Can';我不懂C语言

Can';我不懂C语言,c,debugging,pointers,trie,cs50,C,Debugging,Pointers,Trie,Cs50,我开始用C语言编写这个非常简单的程序,但不知怎的它崩溃了。我不知道为什么,但如果你能看看我的代码,告诉我那将是伟大的 #include <stdio.h> #include <stdlib.h> #include <cs50.h> #include <string.h> typedef struct node { bool is_word; struct node* children[27]; } node; node* roo

我开始用C语言编写这个非常简单的程序,但不知怎的它崩溃了。我不知道为什么,但如果你能看看我的代码,告诉我那将是伟大的

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>

typedef struct node
{
    bool is_word;
    struct node* children[27];
}
node;

node* root;

int main()
{
    root->children[0]=NULL;
}
#包括
#包括
#包括
#包括
类型定义结构节点
{
布尔是一个词;
结构节点*子节点[27];
}
节点;
节点*根;
int main()
{
root->children[0]=NULL;
}

在使用指针之前,必须对其进行初始化。在这个特定的示例中,您很可能会得到一个空指针,因为根据C标准,全局变量应该初始化为0

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>

typedef struct node
{
    bool is_word;
    struct node* children[27];
}
node;

node* root;

int main()
{
    root = malloc(sizeof(node));
    root->children[0]=NULL;
    free(root);
}
#包括
#包括
#包括
#包括
类型定义结构节点
{
布尔是一个词;
结构节点*子节点[27];
}
节点;
节点*根;
int main()
{
root=malloc(sizeof(node));
root->children[0]=NULL;
自由根;
}
问题就在这里

node *root;
您已经声明了root,但尚未定义它。默认情况下,它包含一些垃圾地址或全局为空,这是非法访问的,因此程序崩溃

将根初始化为trie的第一个节点,然后进一步使用它

做这个手术-

root->children[0] = NULL
翻译成someGarbageValue/NULL->children[0]=NULL//毫无意义。 将根目录初始化为第一个节点

要初始化根目录,可以为其分配内存

root = (node *)malloc(sizeof(node));
这将从堆中分配内存,malloc将把分配内存的起始地址存储到根节点指针中

不要忘记释放此内存,以避免使用完后内存泄漏

free(root)

您试图在不首先指向
节点的情况下取消对
根的引用help@islamzidan正确的回答是投票并接受答案。我投票了,但我的声誉不到15。我是新来的,答案将在几分钟内被接受。但是如何初始化答案根?你可以把你的根去掉。我会发布我的答案。更新了答案。更好但是。。。这是我的偏好。我不同意这个答案。通常在调试长代码时,我不会向上滚动查看根或其他实体的类型。它将写在它的前面。始终键入您的malloc以遵循您的组织编码准则,其中大多数准则也包括此准则:)