Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass pointer to pointer behaves weird

I am solving Leetcode problem #94 for in-order traversal of a binary tree.

I cannot understand why – when I use &cpy (currently commented) when calling helper() the program works correctly but not when I use &gResult.

int countNode(struct TreeNode* root)
{
    if(root)
        return 1 + countNode(root->left) + countNode(root->right);
    return 0;
}

void helper(struct TreeNode* root, int** res)
{
    if(root)
    {
        helper(root->left, res);
        *((*res)++) = root->val;
        helper(root->right, res);
    }
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize){
    int *gResult = NULL; 
    *returnSize = countNode(root);
    gResult = (int*)malloc(((*returnSize)) * sizeof(int));
    memset(gResult, 0, (*returnSize) * sizeof(int));   
    int *cpy = gResult;
//    helper(root, &cpy);
    helper(root, &gResult);
    return gResult;
}

Error Snapshot

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The function helper changes the value of the pointer passed to the function by reference.

    *((*res)++) = root->val;
      ^^^^^^^^

So after calling the function the original pointer will not point to the allocated memory.

Thus using an intermediate pointer like in this code snippet

int *cpy = gResult;
helper(root, &cpy);

leaves the pointer gResult unchanged that points to the dynamically allocated memory and is returned from the function inorderTraversal. And the caller of the function can be able to free the allocated memory successfully using the returned pointer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading