Home > Software engineering >  How to return an array in a recursive function?
How to return an array in a recursive function?

Time:12-28

I am a C begginer I was trying to code a merge_sort function. I wrote my code below.

variable "array_global" is the merge between array "a" and array "b", and all that merge proccess works fine, the problem occurs when the function returns "array global", since it seems that it only returns the first element of the array.

For example, if "array_global" is [19, 26], integer pointer "a" which receives the result of the function only receives [19]

What did I did wrong? And why this happens?

Thx in advance

int *merge_sort(int array[], int len)
{
  if (len == 1)
  {
    return array;
  }
  else
  {
    int l1 = (len/2);
    int l2 = len - l1;
    int sub_array_1[l1]; int sub_array_2[l2];
    for (int i = 0; i<l1; i  )
    {
      sub_array_1[i] = array[i];
    }
    for (int i = l1; i<len; i  )
    {
      sub_array_2[i-l1] = array[i];
    }
    int *a = merge_sort(sub_array_1, l1);//Receives array_global value
    int a_size = (sizeof(a)/sizeof(int));
    int *b = merge_sort(sub_array_2, l2);//Receives array_global value
    int b_size = (sizeof(b)/sizeof(int));
    int mult = a_size   b_size;
    int *array_global = malloc(sizeof(*array_global)*mult);
    merge(a, b, a_size, b_size, array_global);
    return array_global;

  }
}

CodePudding user response:

Mistake here:

int a_size = (sizeof(a)/sizeof(int));

should read

int a_size = l1;

sizeof doesn't measure the size of an array on the heap.

Memory leak here:

return array_global;

should be:

free(a);
free(b);
return array_global;
  • Related