我正在尝试练习Binnary树。 我为节点创建了一个结构,为根分配了它,并为左子分配了空间。 我构建了一个返回树大小的函数,但是在尝试初始化左子变量时似乎有错误。
主要功能:
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;
}
节点结构:
typedef struct
{
int data;
struct node* left;
struct node* right;
}node;
我得到的错误:
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|
我做错了什么?
答案 0 :(得分:2)
您在那里遇到错误,因为您尝试使用。而不是 - > 来访问该指针。 typedef struct 也应该是 typedef struct node 。
试试这个:
#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;
}
不要投射 malloc ,因为malloc的返回是 void * 。