0

I wrote the code for a function which sorts an array, which I would then be able to access in main file .

The problem I am facing is that I am not able to understand how pass an array and to sort the array.

Initialization of function.

void sort (int *ary[], int len);

Main function

int main ()
{
    int max [4]= {2,8,5,9};
    sort(&max, 4);
     for (int l =0; l<4;l++)
     {
         cout<< max[l]<< " "<< endl;
     }
    system("pause");
    return 0;
}

function which will sort the array by bubble sort.

void sort (int *ary[], int len )
{
    int temp=0;
    for (int i = 0; i<len; i ++)
    {
        for (int j= 0 ; j<len ;j++)
        {
            if (ary[j]> ary[j+1])
            {
                temp = ary[j];
                ary[j] = ary[j+1];
                ary[j+1]= temp;
            }
        }
    }
}

I get the following error message:

visual studio 2012\projects\problem2\problem2\pract.cpp(11): error C2664: 'sort' : cannot convert parameter 1 from 'int [4]' to 'int *[]'

How do I resolve this error?

David Tansey
  • 5,813
  • 4
  • 35
  • 51

1 Answers1

0

int *ary[] means an array of pointers. You can write int ary[] to take an array:

void sort(int ary[], int len);

Since it's a function parameter, int ary[] means the same as int* ary, so the above is equivalent to:

void sort(int* ary, int len);

Finally, call it like this (because of array-to-pointer decay):

sort(max, 4);
Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157