简体   繁体   中英

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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM