error: request for member 'data' in something not a structure or union|

error: request for member 'data' in something not a structure or union|

我正在尝试练习二叉树。 我为节点创建了一个结构,为根分配了它,还为左儿子分配了 space。 我构建了一个返回树大小的函数,但在尝试初始化左子的变量时似乎出现错误。

主要功能:

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|

我做错了什么?

您在那里遇到错误,因为您尝试使用 . 而不是 -> 访问该指针。 另外 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 的 return 是 void*.