【发布时间】:2015-12-20 13:34:52
【问题描述】:
我正在尝试练习二叉树。 我为节点创建了一个结构,为根分配了它,还为左儿子分配了空间。 我构建了一个返回树大小的函数,但在尝试初始化左儿子的变量时似乎出错了。
主要功能:
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|
我做错了什么?
【问题讨论】:
-
左右都是
struct node *所以要访问他们的会员数据,需要使用-> not。 .. -
还有
typedef struct-->typedef struct node -
指向结构的指针是指向结构的指针,无论嵌套级别如何。当你有一个指向结构的指针时获取一个成员,你使用箭头
->。您已经知道这一点,因为您在例如使用它时。root->left. -
为什么 (node*) malloc(sizeof(node)); ??
-
还是不行。你的意思是 root->left->data 之类的东西吗?
标签: c struct dereference