【问题标题】:Why is my while loop ignoring the NULL condition?为什么我的 while 循环忽略了 NULL 条件?
【发布时间】:2020-01-30 23:09:43
【问题描述】:

我正在尝试做一个将值插入二叉树的函数。 insertbin(...) 中的第一个 while 循环在它移动到下一个元素后等于 NULL 时完全忽略 x 值。我的情况有什么问题吗?

我已经尝试使用 prev 节点来检查条件,但它仍然不起作用。

#include <stdlib.h>
#include <stdio.h>
#include "Queue_arr.h"
tree* createtree() {
    tree*mytree = (tree*)malloc(sizeof(tree));
    mytree->root = NULL;
    return mytree;
}

void insertbin(tree* T, int data) {
    treenode *x, *y, *z;
    int flag = 1;
    z = (treenode*)malloc(sizeof(treenode));
    y = NULL;
    x = T->root;
    z->key = data;
    while (x != NULL) //While the tree isn't empty
    {
        y = x;
        if (z->key < x->key) //If the data is smaller than the existing key to the left
            x = x->sonleft;
        else //Else, to the right
            x = x->sonright;
    }
    z->father = y;
    if (y == NULL) //If y is the root
        T->root = z;
    else
        if (z->key < y->key) //If the data is smaller than the existing key to the left
            y->sonleft = z;
        else //Else, to the right
            y->sonright = z;
}

void insertscan(tree *T) //Scans the data to insert to the tree via insertbin(...)
{
    int data;
    printf("Enter a number (Enter a negative number to stop): \n");
    scanf("%d", &data);
    while (data >= 0)
    {
        insertbin(T, data);
        scanf("%d", &data);
    }

}



void main()
{
    tree* T;
    T = createtree();
    insertscan(T);
}

【问题讨论】:

  • 请删除任何与当前问题无关的代码。如果您可以硬编码对insertbin() 的调用并摆脱所有用户输入内容,这将很有帮助。 minimal reproducible example 越简单越好。
  • malloc 使内存未初始化 stackoverflow.com/a/1538427/3365922 所以你可能有错误的 z-&gt;sonleftz-&gt;sonright
  • 我应该把它改成calloc吗?
  • calloc 几乎适用于您可能会看到的任何实现,尽管从技术上讲,它不能保证初始化指向 NULL 的指针。

标签: c while-loop null


【解决方案1】:

我将 z 定义中的 malloc 更改为 calloc 并解决了它。 一定是因为malloc 没有用NULL 填充您的值。

(感谢用户3365922)

【讨论】:

  • calloc 分配的内存将所有字节设置为 0。如果内存内容被解释为包含浮点或指针类型的对象,那么技术上并不能保证那些浮点点对象将比较等于 0.0,或者那些指针类型对象将比较等于 NULL。但是,在您可能遇到的最常见的平台上,所有位为零的浮点对象将比较等于 0.0,而所有位为零的指针类型对象将比较等于 NULL
  • 不要使用calloc() 来解决缺少初始化的问题。空指针不一定全为零。您需要将字段显式设置为NULL
猜你喜欢
  • 1970-01-01
  • 2019-11-07
  • 2017-06-18
  • 2023-03-20
  • 1970-01-01
  • 2014-01-25
  • 2016-09-08
  • 2020-12-14
  • 2020-02-16
相关资源
最近更新 更多