[英]error: request for member 'data' in something not a structure or union|
I'm trying to practice Binnary trees. 我正在尝试练习Binnary树。 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. 我建立了一个返回树的大小的函数,但是在尝试初始化左子变量时似乎出现了错误。
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 . 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 * 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.