I'm trying to practice binary trees.
I created a struct for node, allocated it for the root and also allocated space for the left son.
I built a function that returns the size of the tree but it seems there is an error while trying to initialize the left son's variables.
The main function:
int main()
{
node* root = (node*) malloc(sizeof(node));//allocate space for root
root->data = 7;
root->left = (node*) malloc(sizeof(node));//allocate space for left son of root
root->right = NULL;
root->left.data = 8;//ERROR HERE!
root->left.left = NULL;//ERROR HERE!
root->left.right = NULL;//ERROR HERE!
printf("size of tree: %d\n", sizeOfTree(root));
return 0;
}
The node struct:
typedef struct
{
int data;
struct node* left;
struct node* right;
} node;
The errors I get:
Error: request for member 'data' in something not a structure or union|
Error: request for member 'left' in something not a structure or union|
Error: request for member 'right' in something not a structure or union|
What am I doing wrong?
You got error there because you try to access that pointer with . instead of ->. Also typedef struct should be typedef struct node.
Try this:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* left;
struct node* right;
}node;
int main(void){
node* root = malloc(sizeof(node));//allocate space for root
root->data = 7;
root->left = malloc(sizeof(node));//allocate space for left son of root
root->right = NULL;
root->left->data = 8;//ERROR HERE!
root->left->left = NULL;//ERROR HERE!
root->left->right = NULL;//ERROR HERE!
printf("size of tree: %d\n", sizeOfTree(root));
return 0;
}
Don't cast malloc because return of malloc is void*.