invalid conversion of pointers using malloc function

#include<stdio.h>
#include<stdlib.h>
struct tree{int data;
struct treeright,left;
};
void insert(struct tree
*,int);
void inorder(struct tree
);
int main()
{ struct tree *head=NULL;
insert(&head,5);
insert(&head,9);
insert(&head,8);
insert(&head,6);
insert(&head,2);
insert(&head,15);
inorder(head);
return 0;
}

void insert(struct tree **head,int i)
{struct tree*temp=*head;
  if(temp==NULL)
   {temp=malloc(sizeof(struct tree));
    temp->right=NULL;
    temp->left=NULL;
    *head=temp;
    }
   else
  { if(temp->data>i)
       insert(&(temp->left),i);
    else
     insert(&(temp->right),i);
   }
}
 
 
void inorder(struct tree*head)
{if(head)
  {inorder(head->left);
    printf("%d",head->data);
    inorder(head->right);
  }
}

here in the above code most of the online compiler are saying invalid conversion of temp=malloc(sizeof(struct tree));

cn any one help me?

2 Likes

I ma not able to understand y conversion of temp=malloc(sizeof(struct tree)); is invalid?

although it is a error and warning free program but during run time is is showing null pointer exception any one please explain

The answer to your problem is "Its a compiler Issue or requirement".

A void pointer in C can be assigned to any pointer without an explicit type-cast.C Language implicitly casts void* to any type, so the cast will be done automatically.

Thus your above code will run absolutely fine in C .Check the error-free/warning free running of your code in C HERE.

But the same code compiled in C++,this will give error http://ideone.com/ibB3Y:

 invalid conversion from ‘void*’ to ‘tree*’  

So in c++ ,implicit conversion of void* to tree * is not allowed/done automatically,explicit type casting is required,So you must explicitly type cast the void pointer returned by malloc to tree* type to fit it into temp .Refer this

temp=(tree*)malloc(sizeof(struct tree));/*Explicit Casting required*/

Please Note Some c++ compiler version ,C++1x and even the The C99 standard does not required the cast.

Hope this help!

2 Likes

Code-chef allow two c++ compilers(gcc 4-3-2 and gcc 4-0-0-8).does both of them require explicit type casting??:slight_smile:

cpluspluscoder:: gcc 4-3-2 requires explicit type casting . But i am not sure about gcc 4-0-0-8 as i always use 4-3-2 gcc version in Codechef.But i think almost all xcept c++1x require explicit type cast.