c - 为什么我的 while 循环忽略 NULL 条件?

标签 c while-loop null

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

我尝试使用上一个节点来检查条件,但仍然不起作用。

#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);
}

最佳答案

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

(感谢用户3365922)

关于c - 为什么我的 while 循环忽略 NULL 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188505/

相关文章:

java - 利用 try catch block 而不是重复进行空检查

java - 设计访问可能为空或 null 的字符串字段的比较器的最佳方法

c - 使用单独的方法是正确的解决方案吗?

创建 I2C 设备驱动程序结构设置

c++ - 为什么 gcc 允许使用大于数组的字符串文字初始化 char 数组?

c - 从不兼容的指针类型警告传递参数

javascript - While 循环在第一次迭代时停止

c# - 为什么在与 null 比较时转换为对象?

PHP 多个 foreach

java - 将字符串反转 (x) 次?