提问人:laveesh sanadhya 提问时间:6/20/2023 最后编辑:12431234123412341234123laveesh sanadhya 更新时间:6/22/2023 访问量:72
变量在此函数中未初始化使用 -- 如何修复?
Variable is used uninitialized in this function -- how to fix?
问:
我在 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();
}
我的错误在哪里?
答:
-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));
这只是我的方式,你可以做你想做的事。
评论
choice
scanf
scanf
choice
choice
int choice;
choice
#include <stdlib.h>
malloc()
choice