Umar Gul
Umar Gul

Reputation: 7

Passing arrays in C++

I'm fairly new to C++, what I'm trying to do is pass the output of the insertion_sort fucntion to the main function. This is my code

#include "include.h"

using namespace std;

int main()
{
    int arr[10] = {12,9,32,1,0,5,13,7,4,2};


    for (int i = 0; i < 10 ; ++i)
    {
        cout << insertion_sort(arr[i]) << endl;
    }
    return EXIT_SUCCESS; 
}

int* insertion_sort(int* arr){
    int key, temp =0;

    for (int i = 0; i < 10; ++i)
    {
        key = i+1;
        while(key >= 0){
            if (arr[key] < arr[key -1])
            {
                temp = arr[key -1];
                arr[key -1] = arr[key];
                arr[key] = temp;
            }
            key--;

        }
    }
    return arr;

}

What I get is

candidate function not viable: no known conversion from 'int' to 'int *' for 1st argument; take the
      address of the argument with &
int* insertion_sort(int* arr);

The insertion sort algorithm is not important here. I just don't understand why the array pointer isn't being passed to the function.

Upvotes: 0

Views: 72

Answers (2)

igon
igon

Reputation: 3046

There are many things going on here:

arr[i] is an integer (type int). You should pass arr which is of type int*.

Your insertion_sort function seems to be modifying the input array in place so you don't need a return value.

Also you should not be invoking insertion sort 10 times. Invoke insertion_sort and then use a for loop to print the sorted array.

Without changing too much:

#include <iostream>

using namespace std;

void insertion_sort(int* arr){
    int key, temp =0;

    for (int i = 0; i < 10; ++i)
    {
        key = i+1;
        while(key >= 0){
            if (arr[key] < arr[key -1])
            {
                temp = arr[key -1];
                arr[key -1] = arr[key];
                arr[key] = temp;
            }
            key--;

        }
    }

}

int main()
{
    int arr[10] = {12,9,32,1,0,5,13,7,4,2};

    insertion_sort(arr);

    for (int i = 0; i < 10 ; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}

Upvotes: 1

slebrun
slebrun

Reputation: 1

I'll stick with answering your question and I'll let your play around and figure the rest out on your own.

Your function signature is int* insertion_sort(int* arr), which means it expects a pointer to an int and will return a pointer to an int.

However, you're passing it arr[i], which is an int, not a pointer to an int.

Try &arr[i].

Happy coding! :)

Upvotes: 0

Related Questions