I'm trying to practice Binnary 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 returnes the size of the tree but it seems there is an error while trying to initialize the left son's variables.
我正在尝试练习Binnary树。我为节点创建了一个结构,为根分配了它,并为左子分配了空间。我构建了一个返回树大小的函数,但是在尝试初始化左子变量时似乎存在错误。
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?
我究竟做错了什么?
1 个解决方案
#1
2
You got error there because you try to access that pointer with . instead of ->. Also typedef struct should be typedef struct node.
你有错误,因为你试图访问该指针。而不是 - >。 typedef struct也应该是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*.
不要转换malloc因为malloc的返回是void *。
#1
2
You got error there because you try to access that pointer with . instead of ->. Also typedef struct should be typedef struct node.
你有错误,因为你试图访问该指针。而不是 - >。 typedef struct也应该是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*.
不要转换malloc因为malloc的返回是void *。