Reputation: 425
I've just started to learn C and trying to make a binary tree with struct. When I try to use addTreeNode in main() I get the following compile errors: "Conflicting types for addTreeNode" and "Passing 'BinaryTree' (aka 'struct BinaryTree') to parameter of incompatible type 'BinaryTree *' (aka 'struct *BinaryTree')"
Am I doing something fundamentally wrong here?
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
struct BinaryTree
{
int data;
struct BinaryTree *left;
struct BinaryTree *right;
};
typedef struct BinaryTree BinaryTree;
BinaryTree *addNode(int element, BinaryTree *tree);
int main(int argc, const char * argv[])
{
BinaryTree *tree;
tree = addTreeNode(2, tree);
return 0;
}
// add the given element element to the tree
BinaryTree *addTreeNode(int element, BinaryTree *tree)
{
if (tree == NULL)
{
tree = malloc(sizeof(BinaryTree));
tree->data = element;
}
else if (element < tree->data)
{
addTreeNode(element, tree->left);
}
else
{
addTreeNode(element, tree->right);
}
return tree;
}
Upvotes: 0
Views: 6644
Reputation: 2232
change this line
tree = addTreeNode(2, tree);
to
tree = addTreeNode(2, &tree);
Your function requires passing by pointer, yet you pass by value.
EDIT:
Since you are allocating your struct in function BinaryTree *addTreeNode
you should change BinaryTree tree;
to BinaryTree *tree;
inside main
. Also your function returns pointer to BinaryTree*
which cannot be assign to a variable of type BinaryTree
Upvotes: 1