简体   繁体   中英

array of typedef struct pointers

I have following in my header file

typedef struct tree_node* TreeNode;

struct tree_node{

    int value;
    void *data;

    TreeNode parent;
    TreeNode left;
    TreeNode right;

};

To create a treenode I am doing following

TreeNode createTreeNode(int value, void *data){

    TreeNode node;

    node = malloc(sizeof(TreeNode*));

    if(node == NULL){
        printf("TreeNode malloc failed!!\n");
        exit(EXIT_FAILURE);
    }


    node->data = data;
    node->value = value;
    node->parent = NULL;
    node->right = NULL;
    node->left = NULL;

    return node;

}

Now I want create array of TreeNodes...how would I do it? I was thinking following

TreeNode *treeNodes;
treeNodes = malloc(26 * sizeof(TreeNode));

And then

treeNodes[a_number_between_0_to_25] = createTreeNode(intNodeValue, NULL);

node = malloc(sizeof(TreeNode*)); will only allocate 4 bytes(or 8 depending on the size of a pointer). This is wrong. Use sizeof(struct tree_node); or you will end up with segmentation violation.

Other than that, your code looks ok. and yes, that is how you can create an array.

Look into VLAs as well(Variable Length Arrays)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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