变量在此函数中未初始化使用 -- 如何修复?

Variable is used uninitialized in this function -- how to fix?

提问人:laveesh sanadhya 提问时间:6/20/2023 最后编辑:12431234123412341234123laveesh sanadhya 更新时间:6/22/2023 访问量:72

问:

我在 c 中有一个与变量相关的问题:

我正在尝试使用递归函数实现二叉树。但是变量存在一些问题。choice

我尝试使变量全局,并使用 ,但仍然错误:static int

'choice' is used uninitialized in this function [-Wuninitialized][text]

我的代码:

#include <stdio.h>

struct node
{
    int data;
    struct node *left, *right;
};

int choice;
struct node *create()
{
   
    printf("do you want to create a node\n 1 yes \n 2 no \n  ");
    scanf("%d",&choice);
    if (choice == 2)
    {
        return NULL;
    }
    else
    {
        struct node *temp;
        temp = (struct node *)malloc(sizeof(struct node));
        printf("enter the data ");
        scanf("%d", &temp->data);
        temp->left = create();
        temp->right = create();
        return temp;
    }
}

int main()
{
    struct node *root;
    root = create();
}

我的错误在哪里?

c 变量 binary-tree

评论

3赞 Tom Karzes 6/20/2023
你应该能够创建一个普通的函数局部变量。调用通常应设置它,但如果调用失败,则可能会取消设置。应检查 from 的返回值,确保其为 1。如果不是,则将取消设置。choicescanfscanfchoice
1赞 Ian Abbott 6/20/2023
该变量是在函数外部定义的,因此它将具有初始值,因此我不知道为什么 C 编译器会在此处警告单元化对象。 AT 文件范围是 的暂定定义。由于该变量没有外部定义,因此它将自动初始化为 0。choiceint choice;choice
0赞 Ian Abbott 6/20/2023
您需要修复 的隐式定义。#include <stdlib.h>malloc()
2赞 Ian Abbott 6/20/2023
您能否确认问题中的代码与您正在编译的代码完全匹配,特别是关于变量的任何声明?choice
0赞 chux - Reinstate Monica 6/21/2023
@laveesh sanadhya,发布的代码不会产生该错误。1) 发布真正的代码和 2) 发布有关所用编译器选项的更多信息。

答:

-2赞 Abdelhak Mez 6/22/2023 #1

我尝试了您的代码,在函数内部和外部都有选择变量,没有错误,即使我打印了工作正常的值。

因此我认为问题与编译器有关,所以我在这里更改了您的代码中的一些

这是一个初始化节点的函数

struct node *initNode(struct node *root)
{
    int number;
    printf("enter the data ");
    scanf("%d", &number);
    root = (struct node *)malloc(sizeof(struct node));
    root->data = number;
    root->left = NULL;
    root->right = NULL;
    return root;
}

那么这就是我使用的打印功能

void printData(struct node *root){
    if(root != NULL){
        printf("%d => ",root->data); // print the value inside root node 
        printData(root->left); // call the function with root->left as the root itself
        printData(root->right);// call the function with root->right as the root itself
    }
}

然后在创建功能中,我只是更改了 else 语句,如下所示

  else
    {
        struct node *root;
        root = initNode(root); // to set the data inside the node 
        root->left = create();
        root->right = create();
        return root;
    }

最后在主要功能

int main()
{
    struct node *root;
    root = create();
    printData(root);
}

我希望这对你有所帮助。

注意:您可以使用 typedef struct 而不是 struct,如下所示:

typedef struct node 
{// it was struct node
    int data;
    struct node *left, *right;
} node; // add this line so your struct will be called with it

//example of struct malloc 
(struct node *)malloc(sizeof(struct node));
//example of typedef struct malloc
(node *)malloc(sizeof(node));

这只是我的方式,你可以做你想做的事。