When dealing with memory to be placed on the stack, there are comfortable ways for doing struct initialization: https://en.cppreference.com/w/c/language/struct_initialization
I want to do the same when the memory is placed on the heap (i.e., when using Dynamically Allocated Memory). To base the discussion, let us use the following struct:
// Definition for a binary tree node.
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
First, I get the address:
struct TreeNode * target = malloc(sizeof(struct TreeNode));
Now what? I offer one possibility (possibility 2: Initialization by assignment), and I have two questions:
- Is my possibility a solution? I could not find resources about doing initializations by assignment.
- Are there any other solutions?
Possibility 1: Direct access through dereference
We do the following:
target -> val = 1;
target -> left = NULL;
target -> right = NULL;
I find this method tedious.
Possibility 2: Initialization by assignment
We do the following:
struct TreeNode sub_target = {.val = val_1, .left = NULL, .right = NULL};
*target = sub_target;
This method seems better, as it allows using all types of struct initializations on the stack but for the heap. It works when I try it, but I do not know if it works in general.