GiffordPG
GiffordPG

Reputation: 53

Copy from an array that has been passed to a function

int getWinnableTwo(char thisArray[9]) { 
    char oneArray[9];

    std::copy(std::begin(thisArray), std::end(thisArray), std::begin(oneArray));

For some reason this does not compile, while using a global array does. I guess it is because the array is passed by reference, but what can I do to make this work?

The error:

mismatched types ‘const std::valarray<_Tp>’ and ‘char*’

Upvotes: 1

Views: 76

Answers (3)

Darem
Darem

Reputation: 1739

You can use std::array which is a container to achive this.

#include <array>
#include <algorithm>

int getWinnableTwo(const std::array<int, 9>& arrayToCopy) {
    std::array<int, 9> destinationArray;

    std::copy(std::begin(arrayToCopy), std::end(arrayToCopy), std::begin(destinationArray));
}

int main()
{
    std::array<int, 9> arrayToCopy{ 1,2,3,4,5,6,7,8,9 };
    int result = getWinnableTwo(arrayToCopy);
}

Upvotes: 2

Alan Birtles
Alan Birtles

Reputation: 36379

When you pass an array as a parameter to a function it decays to a raw pointer. You can see this if you pass an array of a different size to your function, you might be surprised that it compiles:

char test[1];
getWinnableTwo(test);

You don't even need to pass an array:

char test;
getWinnableTwo(&test);

You function is equivalent to:

int getWinnableTwo(char* thisArray) { 
    char oneArray[9];
    std::copy(std::begin(thisArray), std::end(thisArray), std::begin(oneArray));
    return 0;
}

You can't call std::begin and std::end on a raw pointer as the compiler has no way of knowing the size of the data the pointer points to.

One solution is to pass the array by reference:

int getWinnableTwo(char(&thisArray)[9]) { 
    char oneArray[9];

    std::copy(std::begin(thisArray), std::end(thisArray), std::begin(oneArray));
    return 0;
}

This has the additional benefit that you can now only pass char [9] and not any other type.

The more c++ solution is to use std::array instead which you can choose to pass by either reference or value and won't decay to a pointer:

int getWinnableTwo(std::array<char, 9>& thisArray) { 
    std::array<char, 9> oneArray;

    std::copy(std::begin(thisArray), std::end(thisArray), std::begin(oneArray));
    return 0;
}

Upvotes: 4

snake_style
snake_style

Reputation: 1168

Try this one:

int getWinnableTwo(char thisArray[9])
{
    char oneArray[9];
    std::copy(thisArray, thisArray + 9, oneArray);
    return 0;
}

Upvotes: 3

Related Questions