cannot convert 'int' to 'node *'

2k views Asked by At

i am reading a c++ source code, converting infix to postfix i am using turbo c++

 #include <stdio.h>
 typedef struct node
{
  float data;
  struct node *next;
} stack;

void StackInitiate(stack **head)
{
  //error
  if(*head=(stack *)malloc(sizeof(stack))==NULL)
      exit(1);
  (*head)->next=NULL;
}

// I'm getting .. cannot convert 'int' to 'node *' ...

can anybody tell me why so . and how to solve it regards.

full source code here

2

There are 2 answers

0
Some programmer dude On BEST ANSWER

Because of operator precedence the expression

*head=(stack *)malloc(sizeof(stack))==NULL

is actually equivalent to

*head=((stack *)malloc(sizeof(stack))==NULL)

That is, you assign the value of the comparison to *head.

You need to put in your own parentheses to make it correct:

(*head=(stack *)malloc(sizeof(stack)))==NULL

Or better yet use the new operator which is what you rreally should use to allocate object dynamically in C++:

(*head=new stack)==NULL
0
Emil Laine On

Because of operator precedence rules, the following:

if(*head=(stack *)malloc(sizeof(stack))==NULL)

is parsed as

if(*head=((stack *)malloc(sizeof(stack))==NULL))

which is assigning the result of the == NULL comparison to *head.

To compare the new value of *head to null instead, use parentheses to change the precedence:

if((*head=(stack *)malloc(sizeof(stack)))==NULL)

Or even better, separate the assignment from the if condition:

*head = (stack *) malloc(sizeof(stack));
if(*head == NULL)

This convention is more readable and would also avoid similar bugs happening in the future.