2014-04-22 49 views
0

我很难搞清楚如何动态分配内存,然后用该内存初始化一个结构。我试图做一个二叉树,然后设置孩子有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; 
} 
+1

只为初学者,当你需要时,你需要分配用于“单词”的缓冲区。 – DrC

+1

接下来,通常的做法是将子指针设置为NULL以指示不存在。 – DrC

+0

'countchars'的正确拼写实际上是'strlen'(并且您还需要包含''标题)。 –

回答

0

struct node *是指针类型。要访问它的值,你需要对它们进行解引用。下面显示了可能已经打算什么:

typedef struct node_t{ 
    char* word; 
    int count; 
    struct node_t* leftchild; 
    struct node_t* rightchild; 
} node; 

int main(void){ 
    node *rootnode = (node*)malloc(sizeof(node)); 
    //scanf("%s ", rootnode.word); 
    //rootnode.count = countchars(rootnode.word);/*haven't written this func yet*/ 
    rootnode->leftchild = (node*)malloc(sizeof(node)); 

    node* leftchild = rootnode->leftchild; 
    leftchild->word = NULL; 
    rootnode->rightchild = (node*)malloc(sizeof(node)); 

    node* rightchild = rootnode->rightchild; 
    rightchild->word = NULL; 
    return 0; 
} 

注意,scanf行注释 - 你需要的单词缓冲区分配空间之前,你可以阅读到它。我把它作为一个练习给你:)

+0

谢谢这真的为我清除了一些东西。我遇到的一个主要问题是rootnode.leftchild与rootnode-> leftchild不一样。我只是把它写成(* rootnode).leftchild – v3nd3774

+0

使用'(* somePointer).'和使用'somePointer->'是一样的。后者是使得阅读代码更简单的语法糖。 – Tawnos

1

你下面的逻辑是不正确的:

struct node *rootnode=malloc(sizeof(struct node)); 
scanf("%s ",rootnode.word); 
rootnode.count=countchars(rootnode.word);/*haven't written this func yet*/ 

在上面的代码,您已经分配的内存为结构节点。现在是类型为char的指针。到目前为止,您已经将可以存储地址的内存分配到这个变量中。

现在你需要分配内存拷贝到这个特定的变量中。您需要在此查找或定义字符串的最大长度。举一个例子(100)

rootnode.word = malloc(100*sizeof(char)); 
// Now you can use this memory further in your program. 

BTW需要将逻辑写入自由存储器为好。

+0

次要评论 - sizeof(char)明确等于1. – DrC

1

仅供初学者,您需要在需要时分配用于“单词”的缓冲区。接下来,通常的做法是将子指针设置为NULL以指示不存在。

所以

node.count=strlen(string); /* hope this is what you want, if not use strlen(string on next line) */ 
node.word = malloc(node.count+1); 
strcpy(node.word, string); 
node.leftChild = node.rightChild = NULL;