Smart pointer to dynamically allocate an array

Hello! I recently was introduced to use smart pointer to dynamically allocate an array using "unique_ptr<int[]> array(new int[])"

All is going well until I need to use a function to sort it!! I can't figure out how to pass this pointer to another function.

Here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include<iostream>
#include<memory>
#include<fstream>

using namespace std;

void sortArray(int *, int);

int main()
{
   int student;
   
   cout<<"How many students do you wish to analyse?"<<endl;
   cin>>student;
   
   unique_ptr<int[]> scores(new int[student]{});
   unique_ptr<int[]> num(new int[student]{});
   
   ifstream in;
   in.open("scores.txt");
   
   for(int x=0; x<student; x++)
   {
      in>>scores[x]>>num[x];
   }
   in.close();
   
   sortArray(scores, student);
   cout<<scores[0];
   
}

void sortArray(int *pointer, int size)
{
   cout<<"I am in!";
   //Haven't started coding this part yet 
}


When I compile, i get this error message on line 29:
"no matching function for call to 'sortArray"

and this one on my function prototype:
"candidate function not viable: no known conversion from 'unique_ptr<int[]>' to 'int*' for 1st argument"
Last edited on
The sort function expects a raw pointer (this is correct, the function does not own the array object).
Retrieve the underlying raw pointer with std::unique_ptr::get() and pass that to the function.
http://en.cppreference.com/w/cpp/memory/unique_ptr/get

1
2
// sortArray(scores, student);
sortArray(scores.get(), student);
Oh my god! You're a godsend JLBorges! Thank you so much!
OP: the ctor for int's probably OK but in general prefer std::make_unique over the use of the new operator -
unique_ptr<int[]> scores = std::make_unique<int[]>(student);
http://stackoverflow.com/questions/37514509/advantages-of-using-make-unique-over-new-operator
Topic archived. No new replies allowed.