【问题标题】:error: request for member 'data' in something not a structure or union|错误:在非结构或联合中请求成员“数据”|
【发布时间】: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


【解决方案1】:

那里出现错误,因为您尝试使用 . 而不是 -> 访问该指针。 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;
}

不要强制转换 ma​​lloc,因为 malloc 的返回是 void*

【讨论】:

  • @Michi typedef structtypedef struct node 有什么区别?
猜你喜欢
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 2014-02-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
相关资源
最近更新 更多