user906357
user906357

Reputation: 4685

Returning a pointer to an array C++

I have a function that needs to return a pointer to an array:

int * count()
{
    static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    return &myInt[10];
}

inside my main function I want to display one of the ints from that array, like here at index 3

int main(int argc, const char * argv[])
{   
    int myInt2[10] = *count();

    std::cout << myInt2[3] << "\n\n";
    return 0;
}

this however gives me the error: "Array initializer must be an initializer list"

how do I create an array within my main function that uses the pointer to get the same elements as the array at the pointer?

Upvotes: 0

Views: 177

Answers (2)

pippin1289
pippin1289

Reputation: 4939

A few problems in your code:

1) you need to return a pointer to the beginning of the array in count:

return &myInt[0];

or

return myInt; //should suffice.

Then when you initialize myInt2:

int* myInt2 = count();

You can also copy one array into the other:

int myInt2[10];
std::copy(count(), count()+10, myInt2);

Note copying will create a second array using separate memory than the first.

Upvotes: 4

user541686
user541686

Reputation: 210352

You don't need pointers, references are fine.

int (&count())[10]
{
    static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    return myInt;
}

int main(int argc, const char * argv[])
{   
    int (&myInt2)[10] = count();

    std::cout << myInt2[3] << "\n\n";
    return 0;
}

Upvotes: 1

Related Questions