简体   繁体   English

返回指向数组的指针C ++

[英]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 在我的主要函数中,我想显示该数组中的一个整数,例如此处的索引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: 1)您需要在count中返回一个指向数组开头的指针:

return &myInt[0];

or 要么

return myInt; //should suffice.

Then when you initialize myInt2: 然后,当您初始化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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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