首页 文章

使用动态分配的内存初始化结构

提问于
浏览
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;
}

3 回答

  • 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 行已注释 - 您需要为字缓冲区分配空间,然后才能读入它 . 我把它作为练习留给你:)

  • 1

    您的以下逻辑不正确:

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

    在上面的代码中,您已为struct节点分配了内存 . 现在word是char类型的指针 . 到目前为止,您已经分配了可以将地址存储到此变量中的内存 .

    现在,您需要分配内存以复制到此特定变量中 . 您需要在此处查找或定义字符串的最大长度 . 举个例子(100)

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

    顺便说一句,你需要编写逻辑来释放内存 .

  • 1

    对于初学者来说,你需要在需要时分配用于“word”的缓冲区 . 接下来,通常的做法是将子指针设置为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;
    

相关问题