我很难搞清楚如何动态分配内存,然后用该内存初始化一个结构。我试图做一个二叉树,然后设置孩子有NULL作为他们的'单词',这是我可以测试NULL,并根据需要插入更多的节点。这是迄今为止我所拥有的。使用动态分配内存初始化结构
#include <stdio.h>
#include <stdlib.h>
struct node{
char* word;
int count;
struct node* leftchild;
struct node* rightchild;
};
int main(void){
struct node *rootnode=malloc(sizeof(struct node));
scanf("%s ",rootnode.word);
rootnode.count=countchars(rootnode.word);/*haven't written this func yet*/
rootnode.leftchild=malloc(sizeof(struct node));
struct node* leftchild = rootnode.leftchild;
rootnode.leftchild.word=NULL;
rootnode.rightchild=malloc(sizeof(struct node));
struct node* rightchild = rootnode.rightchild;
rootnode.rightchild.word=NULL;
}
只为初学者,当你需要时,你需要分配用于“单词”的缓冲区。 – DrC
接下来,通常的做法是将子指针设置为NULL以指示不存在。 – DrC
'countchars'的正确拼写实际上是'strlen'(并且您还需要包含''标题)。 –