简体   繁体   English

如何在函数中返回指针数组?

[英]How do I return an array of pointers in a function?

So I have an array of pointers that references 3 instances of a class, I need to create a function that gets the references to those 3 instances and returns it into that array. 所以我有一个引用3个类的实例的指针数组,我需要创建一个函数来获取对这3个实例的引用并将其返回到该数组中。

Here is what I have been trying: 这是我一直在尝试的:

#include<cstdlib>
#include<cinttypes>
#include<random>

//Random number generator
uint8_t rand(uint8_t max){
    std::default_random_engine generator;
    std::uniform_int_distribution<uint8_t> distribution(0,max);

    return distribution(generator);
}

class MyClass{
    //...
}
myClass[100];

MyClass * getReferences(){ //What should the type of this be?
    MyClass * arrayOfPointers[3];

    for(uint8_t i=0;i<2;++i){
        arrayOfPointers[i]=&myClass[rand(2)];
    }

    return arrayOfPointers;
}

int main(){
    MyClass * arrayOfPointers[3]=getReferences();

    return EXIT_SUCCESS;
}

As mentioned you are returning a pointer to a local variable which is incorrect. 如前所述,您将返回一个指向不正确的局部变量的指针。

Use standard library containers to avoid the pitfalls and woes of C-style arrays. 使用标准库容器来避免C风格数组的陷阱和困境。

std::array<MyClass *, 3> getReferences()
{
    std::array<MyClass *, 3> arrayOfPointers;

    for(int i=0; i < 2; ++i) // don't use tiny int types of small for loops. it's not faster and it's harder to maintain
    {
        arrayOfPointers[i] = &myClass[rand(2)];
    }

    return arrayOfPointers;
}

int main()
{
    std::array<MyClass *, 3> arrayOfPointers = getReferences();
}

Returning a pointer to a local variable is incorrect in C++. 在C ++中返回指向局部变量的指针是不正确的。 It can lead in memory violation errors. 它可能导致内存冲突错误。 If you want to return an array from the function you should use dynamic memory allocation. 如果要从函数返回数组,则应使用动态内存分配。 MyClass * arrayOfPointers = new MyClass[3]; . Don't forget to delete it, after using. 使用后别忘了删除它。 delete[] arrayOfPointers;

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

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