Ava
Ava

Reputation: 6053

new operator (Error :expected expression before struct)

struct node* NewNode(int data)
{
  struct node* node = new(struct node);
  node->data = data;
  node->left = NULL;
  node->right = NULL;
  return(node);
}

I am getting this error in first line of the function. Cant figure out whats wrong? Thanks.

Upvotes: 0

Views: 2236

Answers (2)

COrthbandt
COrthbandt

Reputation: 191

The "new" keyword hints at this being C++. In C++ the "struct TYPENAME" construct is largely obsolete, you can simply use TYPENAME instead. The C way of typedefing a type name from a named struct is implicit in C++.

node* NewNode(int data)
{
  node* pnode = new node;
  pnode->data = data;
  pnode->left = NULL;
  pnode->right = NULL;
  return(pnode);
}

should work just fine if this is C++. Please note that using the same name for a type and a variable is not a good idea. Some naming convention (hungarian or anything) helps.

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283684

This code compiles perfectly fine under Comeau try-it-out:

#define NULL 0

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

struct node* NewNode(int data)
{
  struct node* node = new(struct node);
  node->data = data;
  node->left = NULL;
  node->right = NULL;
  return(node);
}

Upvotes: 2

Related Questions