Home > Mobile >  [Solved by rewrite]Problem with passing pointer and recursive function
[Solved by rewrite]Problem with passing pointer and recursive function

Time:07-19

I'm really newbie to c programing, and I have no idea how can I make it work. I want to make sort function that sorting array of integers by using 2 argument. I want to use recursive on sort function. and sorting from end of array to first. by ascending order.

void  ft_sorting(int *arr, int size);

but I don't know what went wrong. It totally out of my understanding with pointer and array. right now I really have no idea. Can some one pointing what I did wrong. And what I need to learn and fix. Thank you!

void    ft_recure(int *a, int *b, int j, int k)
{
    if (--j >= 0)
    {
        if (a[k] < b[j])
        {
            a[k] = b[j];
        }
        else
        {
            ft_recure(a[k], b[j], j, k);
        }
    }
    else
        return a[k];
}

void    ft_sort(int *tab, int size)
{
    int i;
    int h;
    while (size > 0)
    {
        i = size;
        h = i;
        tab[size] = ft_recure(tab, tab, i, h);
        size--;
    }
}

and also I try this.

int  ft_recurs(int x, int y, int a, int b)
{
    int j;
    
    j = a;
  if( a > 0)
  {
    
    if(*x < *(y - 1);)
    {
        b = *(y - 1);
      *x = b;
    }
    ft_recurs(*x,*(y - 1),a - 1, b);
  }
  else
  {
    return *x;
  }
}

void  ft_sort_int_tab(int *tab, int size)
{
  int memo;
  int i;

  while(--size >= 0)
  {
    i = size;
    tab[size] = ft_recurs(tab[i], tab[size], i, memo);
  }
}

CodePudding user response:

In the first approach, you did improper when calling API again:

    void    ft_recure(int *a, int *b, int j, int k)
    {
        if (--j >= 0)
        {
            if (a[k] < b[j])
            {
                a[k] = b[j];
            }
            else
            {
                ft_recure(a[k], b[j], j, k);
            }
        }
        else
            return a[k];
    }

a and b input to API ft_recure is a pointer but in ft_recure(a[k], b[j], j, k); it is value. You should correct this as: ft_recure(&a[k], &b[j], j, k); if you expect to input the address of k and j elements.

In your alternative usage:

    int  ft_recurs(int x, int y, int a, int b)
    {
        int j;
        
        j = a;
      if( a > 0)
      {
        
        if(*x < *(y - 1);)
        {
            b = *(y - 1);
          *x = b;
        }
        ft_recurs(*x,*(y - 1),a - 1, b);
      }
      else
      {
        return *x;
      }
    }

The input is value but in the function you are using *x andn *(y-1) is not really a proper way. May be you could try int ft_recurs(int x[], int y[], int a, int b). But if so, you also need to provide pointer address at ft_recurs(*x,*(y - 1),a - 1, b); and then the issue come back to similar to first approach.

  • Related