初始化c中的树



im试图初始化树数据结构,但每次调用initTree((时;我的程序在没有任何输出的情况下终止我的initTree((:

Tree* initTree(){
Tree* tree = (Tree*) malloc(sizeof(Tree));
tree->root = NULL;
tree->root->left = NULL;
tree->root->right = NULL;
tree->height = 0;
return tree;
}

然而,当我移除2条线tree->root->left = NULL;tree->root->right = NULL;时我的程序运行良好,有什么解释吗??

函数调用未定义的行为,因为使用了空指针
tree->root = NULL;
^^^^^^^^^^^^^^^^^^  

访问这些语句中的内存

tree->root->left = NULL;
^^^^^^^^^^
tree->root->right = NULL;
^^^^^^^^^^

也就是说,指针tree->root没有指向有效对象。因此,上述两种说法毫无意义,应予以删除。

您不能使用空指针来访问内存。

最新更新