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

How to return an array in a recursive function?

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]

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

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;

  }
}

>Solution :

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;
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