Click here to Skip to main content
15,883,978 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
//The following line of code gives above mentioned error
//printf("%d",root->left->info);
// is there any flaw in the algorithm or coding



C#
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>


typedef struct Node
{
    int info;
    struct node* left;
    struct node* right;
}node;

void insert(node *root,int item)
{
    node *parent,*cur;
    parent=NULL;
    cur=root;
    while(cur!=NULL)
    {
        parent=cur;
        if(item<=cur->info)
        cur=cur->left;
        else
        cur=cur->right;
    }
    if(parent==NULL)
    {
        root->info=item;
        root->left=NULL;
        root->right=NULL;
    }
    else if(item<parent->info)
    {
        node *newNode=(int*)malloc(sizeof(node));
        newNode->info=item;
        newNode->left=NULL;
        newNode->right=NULL;
        parent->left=newNode;
    }
    else
    {
        node *newNode=(int*)malloc(sizeof(node));
        newNode->info=item;
        newNode->left=NULL;
        newNode->right=NULL;
        parent->right=newNode;
    }
}


int main()
{
    node *root=(node*)malloc(sizeof(node));
    root->info=6;
    root->left=NULL;
    root->right=NULL;
    insert(root,4);
    printf("%d",root->left->info);
    getch();
}
Posted

1 solution

The problem lies in the definition of your node structure:
C++
typedef struct Node
{
    int info;
    struct node* left;    // <----
    struct node* right;   // <----
}node;

There is no "struct node", but only a "struct Node" (uppercase). And hence is left a pointer to a yet undefined structure, which the compiler gladly accepts until you try to dereference it. So define left as "struct Node*" and everything will be fine.

Btw. you cannot define left as "node*" because the "node" has not yet been defined at that point.
 
Share this answer
 
v2
Comments
pasztorpisti 9-Aug-13 15:45pm    
Nice catch!
nv3 9-Aug-13 16:39pm    
Thank you.
H.Brydon 9-Aug-13 20:52pm    
Yeah me too, I missed it as well. +5
nv3 10-Aug-13 4:01am    
Thanks, Harvey.
Brady Bar 10-Aug-13 0:08am    
:) thanks nv3.i just didn't see it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900