简体   繁体   English

二叉树节点的 C 声明结构

[英]Structures in C declaration of a node for binary tree

struct node * newNode(int data)

Can anybody give me an insight what is struct node* ?任何人都可以让我了解什么是struct node*吗? what does node* is representing? node*代表什么?

The intention behind asking this question is :问这个问题的意图是:

int main(void){
  struct node *node1,*node2;
  node1 =(struct node*)malloc(sizeof(*node1));
  node2=(struct node*)malloc(sizeof(*node2));
  node1->value=7;
  node1->left=node2;
  node1->right=NULL;
  node2->value=9;
  node2->left=NULL;
  node2->right=NULL;
  printf("%d",node1->left->value);
}

This is working fine !这工作正常! now here why struct node* is casted?现在这里为什么 struct node* 被强制转换? Doing struct *node is showing error.执行 struct *node 显示错误。

Seems like you are doing something related to binary tree.好像你正在做一些与二叉树相关的事情。 First Of all, instead of these 2 lines :-首先,而不是这两行:-

  node1 =(struct node*)malloc(sizeof(*node1));
  node2=(struct node*)malloc(sizeof(*node2));

Use these (recommended):-使用这些(推荐):-

  node1=(struct node*)malloc(sizeof(struct node));
  node2=(struct node*)malloc(sizeof(struct node));

Also, the malloc returns a void pointer and it must be casted into the data type on the Left Hand Side.此外,malloc 返回一个空指针,它必须转换为左侧的数据类型。

node1= malloc( ...);

On the left hand side (above statement) the data type of node1 is struct node and so its pointer type will be struct node * .在左侧(上面的语句),node1 的数据类型是struct node ,因此它的指针类型将是struct node * Therefore, struct node* is used as a cast as below.因此, struct node*用作如下强制转换。

node1=(struct node*)malloc( ... );
struct NODE {
   char data[12];
   struct NODE* newNode;    //reference pointer
};

Here NODE* is just a reference structure pointer inside the structure, which can be used to hold the address of the variable declared inside the structure.这里的NODE*只是结构内部的一个引用结构指针,可以用来保存结构内部声明的变量的地址。

Don't get confused : *node :used as pointer 
          where as : node* :is used as reference

  struct NODE{
   char data[12];
   char *next;
};

typedef struct DATA Sample;

Sample *hptr = NULL;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM