【问题标题】:initializing a tree in c在c中初始化一棵树
【发布时间】:2023-04-07 22:54:02
【问题描述】:

我试图初始化一个树数据结构,但每次我调用 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; 我的程序运行良好,有什么解释吗??

【问题讨论】:

    标签: c tree undefined-behavior null-pointer memory-access


    【解决方案1】:

    函数调用未定义的行为,因为使用了空指针

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

    在这些语句中访问内存

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

    即指针tree->root 没有指向有效对象。因此,上面的两个语句没有意义,应该删除。

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

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 2017-10-21
      • 2010-10-21
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多