dimanche 4 décembre 2016

Passing unique_ptr

#include <iostream>
#include <memory>

std::unique_ptr<int[]> addElement(int *myNumbers, int sizeOfArray);
void printArray(int * arr_ptr, int sizeOfArray);

int main()
{
    const int SIZE = 5;
    int myNumbers[SIZE] = {18, 27, 3, 14, 95};

    std::unique_ptr<int[]> newCopy(new int[SIZE]);
    newCopy = addElement(myNumbers, SIZE);

    std::cout << "myNumbers: ";
    printArray(myNumbers, SIZE);

    std::cout << "newCopy: ";
    printArray(newCopy, SIZE + 1);


    return 0;
}

std::unique_ptr<int[]> addElement(int *myNumbers, int sizeOfArray)
{
    std::unique_ptr<int[]> newArray(new int[sizeOfArray + 1]);

    newArray[0] = 0;
    for(int i = 0; i < sizeOfArray; i++)
    {
        newArray[i + 1] = myNumbers[i];
    }

    return newArray;
}

void printArray(int * arr_ptr, int sizeOfArray)
{
    for(int i = 0; i < sizeOfArray; i++)
    {
        std::cout << arr_ptr[i] << ' ';
    }

    std::cout << std::endl;
}

When trying to call printArray(newCopy, SIZE + 1); I get the compiler error cannot convert 'std::unique_ptr<int []>' to 'int*' for argument '1' to 'void printArray(int*, int)'

I have read several similar questions on here yet I can't seem to find the solution to passing the int[] and the unique_ptr<int[]> to the printArray function.


std::cout << "newCopy: ";
for(int i = 0; i < SIZE + 1; i++)
{
    std::cout << newCopy[i] << ' ';
}

Does what I would like

std::cout << "newCopy: ";
printArray(newCopy, SIZE + 1);

to do

Aucun commentaire:

Enregistrer un commentaire