1

I'm learning structs in C and trying to make a binary tree. Here's the tree struct:

struct BinaryTree
{
    int data;
    struct BinaryTree *left;
    struct BinaryTree *right;
};
typedef struct BinaryTree BinaryTree;

void addTreeNode(int element, BinaryTree *tree);

int main(int argc, const char * argv[])
{
    BinaryTree tree;
    addTreeNode(2, &tree);
    return 0;
}

Now here's what I don't understand:

void addTreeNode(int element, BinaryTree *tree)
{
    *tree = {element, NULL, NULL};
}

I am not trying to do anything useful inside this function for now, but I don't understand why I get a parsing issue at this line. As far as I understand I take a pointer to a tree, dereference it and initialize it. Why the compile error?

user3614293
  • 385
  • 5
  • 13
  • 3
    You may want to add the actual error that gets printed to the question. – Fantastic Mr Fox Jun 01 '14 at 22:43
  • 2
    That's not *initialization*, it's *assignment*. – Jonathon Reinhart Jun 01 '14 at 22:45
  • Error: prog.c:35:13: error: expected expression *tree = {element, NULL, NULL}; – user3614293 Jun 01 '14 at 22:52
  • The code does not actually add a node to the tree, it only initializes the current node. To add a node would require a malloc, setting the right entry in the passed note to point to the new node, setting the left entry in the new node to point to the passed node, set the value entry, and set the right entry to NULL. – user3629249 Jun 02 '14 at 06:57

3 Answers3

3

In general ANSI C instances of structures can only be initialized with a list when declared, e.g.

BinaryTree tree = {element, NULL, NULL};

would work, but not after the fact as you tried.

For more look at expected expression before token

Community
  • 1
  • 1
paisanco
  • 4,098
  • 6
  • 27
  • 33
1

You can fix this particular problem by using:

void addTreeNode(int element, BinaryTree *tree)
{
    tree->data = element;
    tree->left = NULL;
    tree->right = NULL;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

the synthax that you usd for *tree = {element, NULL, NULL}; is called an aggregate initializer, and it not allowed for an assignment.

Use should use an explicit initialization:

tree->data = element;
tree->left = NULL;
tree->right = NULL;
quantdev
  • 23,517
  • 5
  • 55
  • 88