I have a homework assignment and within it I need to allocate memory to a pointer which points to an array of pointers (pNode**). Below is the function which receives an array of an array of pointers, and allocates memory for it and all the relevant pointers & data inside.
In short, the function should allocate memory for a pointer that points to an array of Node pointers.
**NOTE: I have removed certain elements from the function which are irrelevant to my question. The function newGNode allocates memory for the Node struct
int getChildren(pNode** childrenNodes)
{
*childrenNodes = (pNode*)malloc(sizeof(pNode));
for (int i = 0; i < NUM_OF_CHILDREN; i++)
{
childrenNodes[i] = (pNode *)newGNode();
}
return numOfChildren;
}
This is how I call it within the main function:
int main()
{
pNode * ng = NULL;
int test = getChildren(&ng);
}
No matter what I tried to do I cannot seem to get the allocation "stick" in the main function. Inside the getChildren function I can see within the debugger that memory has been allocated precisely as I want it. However when the function returns to the main, the ng pointer seems to be corrupted since the debugger is telling me that it is unable to read the memory.
I have searched online and tried different things but none seem to work. Does anyone have any idea why this is not working as intended? I'm guessing something within the memory allocation is wrong, but can't seem to figure out what.
Here is one question which is similar to mine, but it didn't really help me
Thank you!
1) You call
getChildren()
with two arguments, but it is expecting only one:2) You want an array but reserve space for a single
pNode
:Change to
EDIT:
It seems that you want an array of pointers, then
ng
must be declared as:you need 3 levels of indirection to receive
ng
:and reserve space for an array of pointers:
*childrenNodes = malloc(sizeof(pNode *) * NUM_OF_CHILDREN);
An example with
int
s:But
***
is considered bad style, instead: