将结构实例初始化为NULL时出错

时间:2014-11-18 15:03:49

标签: c

我正在编写一个实施BST的程序,我为此宣布了两种结构。

struct node
{
 int data;
 struct node *link[2];
};

struct tree
{
 struct node *root;
};

typedef struct node node;
typedef struct tree tree;

然后我写了一个函数来插入元素。

void insert_iter(tree *tree, int data);

但是在我的main()函数中,我感到困惑的是,我初始化为NULL的东西。所以,我在main()函数中完成了这个。

tree *tree=NULL;

它给出了分段错误的错误。 但后来我意识到我的insert_iter()函数中的第一个条件调用了tree-> root,所以这个错误肯定会发生。

但后来我对如何初始化这个感到困惑。怎么继续这个?

编辑:我已更新所需的代码!!

这是main()函数

int main()
{

tree *tree=NULL;  // all the confusion is regarding this

printf("hello");   // for debugging
//*tree->root=NULL;  // tried this one but it was wrong
int value,choice;
while(1)
{
    printf("enter the element : ");
    scanf("%d",&value);

    insert_iter(tree,value);

    printf("do you want to enter more : 0 or 1 : ");
    scanf("%d",&choice);

    if(choice==0)
        break;
}

return 0;
}

这是我用来插入元素的函数

void insert_iter(tree *tree, int data)
{

if(tree->root==NULL)
    tree->root=newNode(data);  // function to make a new node
else{

node *it=tree->root;
int dir;
while(1)
{
    dir=data>it->data;
    if(it->link[dir]!=NULL)
        it=it->link[dir];
    else
    {
        it->link[dir]=newNode(data);
        break;          
    }
}}}

1 个答案:

答案 0 :(得分:-1)

tree *tree=NULL;  // all the confusion is regarding this

// the above is setting a pointer to NULL, which is ok


*tree->root=NULL;  // tried this one but it was wrong

// the above is setting a 
// (not initialized to point to any specific memory) 
// offset in the tree struct variable 
// (that offset is not pointing any specific memory)
// to set the first 4 bytes of that memory to NULL
// which should/will cause a seg fault event due to undefined behaviour 

// a workable solution might be:

tree *pTree = malloc( sizeof(tree) );

// and then this would work:

tree->root = NULL; // notice no '*' dereference needed

//I would also strongly suggest that the variable names be different 
//than the struct names, and not just in the capitalization of the name.  
//The use of different names will greatly enhance
//the readability and understandability and clarity of the code 
//(and will avoid any misunderstandings by the compiler and future maintainer)