c - 将未初始化的值解析为函数

标签 c memory initialization binary-search-tree

我正在尝试编写一个小程序,遍历数组中的数字列表并将它们插入到二叉搜索树中。这是我拥有的:

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

typedef struct node_t node_t;

struct node_t {
    int data;
    node_t *left;
    node_t *right;
};

int insert(node_t *node, int n);

int main(void) {
    int array[8] = {5, 8, 3, 6, 9, 2, 4, 7};
    int i;
    node_t *root;

    for (i = 0; i < 8; i++) {
        insert(root, array[i]);
    }

    return 0;
}

int insert(node_t *node, int n) {

    if (node == NULL) {
        node = malloc(sizeof node);
        node->data = n;
        return 1;
    }

    if (n > node->data) {
        insert(node->left, n);

    } else if (n < node->data) {
        insert(node->right, n);

    } else {
        return -1;
    }

    return 0; // Suppress 'control reaches end of non-void function'
}

当我用 gcc 编译时,我收到一条警告说“'root' 可能在这个函数中使用未初始化的”。运行它会导致错误(至少在 Windows 上),但是,在 main() 中打印出 root->data 会产生 0。

我试图实现的想法是 insert() 函数检查指向输入节点的指针是否为 NULL,以便它可以对其进行 malloc。此外,由于递归的处理方式,插入的数字应该插入该节点。如果节点不等于 NULL,那么我将在应该插入数字的节点一侧再次递归调用 insert()

我明白这不起作用的原因与指针 root 没有被定向到任何地方有关,也不是 root->left/root ->right,但是,我不知道我能做些什么来解决这个问题。任何帮助将不胜感激,谢谢!

最佳答案

您发布的代码可能存在更多问题,但我在下面列出了一些问题。

因为它是你需要分配内存的节点,如果它包含 NULL,你需要改变这个:

if (node->data == NULL) {

对此:

if (node == NULL) {

此外,您还需要启动根节点,因为它只包含当时发生在堆栈中的任何内容,并且它可能为 NULL 也可能不是 NULL(即您要在插入函数中比较的内容)。所以像这样启动它:

node_t *root = NULL;

最后一件事是将 malloc 更改为 calloc 函数(或单独在内存上将 memset 设置为零)。否则变量 node->left 和 node->right 可以包含非 NULL 值,这可能导致使用未初始化的内存。

关于c - 将未初始化的值解析为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40573209/

相关文章:

c++ - 如何将类中的静态常量结构用作真正的常量 - 即数组大小

c++ - "Triangle"与 VS2012?

c++ - 如何将 strncpy() 转换为 WCHAR

ios - swift : Game starts to lag mid way

iphone - 有没有像 substringFromIndex 这样使用更少内存的函数?

c++ - 初始化枚举类类型的二维 std::array (C++11)

java - 使用初始化 block 有什么好处?

c - select() 在 non_blocking 手动超时 connect() 调用的繁重条件下失败

c - 解释这个汇编代码

sql - 轻量级数据库(SQL 或 NoSQL)