gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:27 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com