0
void arrFromTree(struct TreeNode* node, int *arr)
{
    static int size=4;
    static int i =0;
   if(node==NULL)
   {
       return;
       
        }
   
    arrFromTree(node->left,arr);
     arr[i]=node->val; 
    printf("arr at %d:%d\n",i,arr[i]);
    i++;
    arr=realloc(arr,(size)*sizeof(int)); 
    size=size+4;
   // printf("val:%d\n",node->val);
    arrFromTree(node->right,arr);
    
}
int kthSmallest(struct TreeNode* root, int k){
    int *arr=(int*)malloc(sizeof(int));
    arrFromTree(root,arr);
    return k;

    
}

I was solving a leet code question , I am unable increase the size of the memory block using realloc(), I tried directly allocating the memory using malloc and it works fine don't know what's the issue, is the it creating issue because I am using recursion here?

  • 4
    Function args are passed by value in C. It means `arr` is a local variable and setting it inside a function does not change the caller's pointer value. See the duplicate post for more details and ways to fix. – kaylum Jul 08 '22 at 05:26
  • For example: `arrFromTree(node->left,arr); arr[i]=node->val;` when the function call returns the `arr` pointer may have been realloced inside the function and the second statement in the caller will not be accessing the realloced pointer but rather the original (likely freed) pointer. – kaylum Jul 08 '22 at 05:28
  • Oh, so if we pass pointer to a function, we can make changes to value pointed by it and it will reflect out of the function? and when we make changes to the pointer address itself it won't be reflected out of the function? – Adi Manav Jul 08 '22 at 05:47
  • Correct. You only change the copy you got from caller – Gerhardh Jul 08 '22 at 06:35

0 Answers0