简体   繁体   English

将内存分配给结构内的结构

[英]Allocating memory to structure within structure

I'm trying to allocate memory for the code,of which i've only included excerpts from the actual program, that follows below, the problem I am having is that i don't know how to allocate memory to the type Key that lies within BStree_node this leads to the issue of segmentation errors when i try to assign values to variables within Key. 我正在尝试为代码分配内存,以下仅包括实际程序的摘录,如下所示,我遇到的问题是我不知道如何将内存分配给位于的Key类型当我尝试为Key中的变量赋值时,这会导致BStree_node中的分段错误问题。

typedef int Data_Item;
typedef char* Sub_Key;
typedef struct {Sub_Key key1; Sub_Key key2;} Key;



struct BStree_node{
    Key key;
    Data_Item data;
    struct BStree_node *left, *right;
}
typedef struct BStree_node BStree_node;
typedef BStree_node** BStree;

BStree bs_tree_ini(void){
    BStree tempTreePointer;
    tempTreePointer = malloc(sizeof(BStree_node*));

    BStree_node *tempNode;
    tempNode = malloc(sizeof(BStree_node));
    tempNode = NULL;

    tempTreePointer = &tempNode;

    return tempTreePointer;

}

You could initialize your node like this, using calloc to zero the memory to initialize all the fields properly: 您可以像这样初始化您的节点,使用calloc将内存清零以正确初始化所有字段:

BStree_node *init_node()
{
   BStree_node *rval = calloc(1,sizeof(BStree_node)); // so all data & pointers are zeroed
   return rval;
}

use it like this: init main, and only left. 像这样使用它:init main,仅左。 right stays zeroed: no right node for that main node. 右侧保持零:该主节点没有右侧节点。

int main()
{
    BStree_node *head = init_node();
    head->left = init_node();
    ...

    return 0;
}

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

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