返回指向对象数组的指针
returning a pointer to an array of objects
我在返回指向对象数组的指针时遇到问题,特别是如何定义返回类型,我只是无法获得返回的指针......
month* year()
{
month* p;
month arr[12] = { month(31), month(28), month(31), month(30), month(31), month(30), month(31), month(31), month(30), month(31), month(30), month(31) };
p = arr;
return p;
}
我也一直在做实验,我担心即使我让它返回,我仍然可以从 main 访问对象吗?这只允许我访问我选择的第一个元素(不是第一个元素,我首先尝试访问(,并且不会给我内容:
int** createArray()
{
int n1 = 1;
int n2 = 2;
int n3 = 3;
int* p[3];
p[0] = &n1;
p[1] = &n2;
p[2] = &n3;
int** j = p;
return j;
}
int main()
{
int** point = createArray();
*point[2] = 5;
cout << *point[1] << endl;
cout << *point[2] << endl;
}
更新:我应该提到我必须在这个项目中使用数组和指针来参加我的课程。我理解我关于局部变量的(愚蠢的(错误,但即使我把它变成一个类,我对返回类型也有同样的问题:
class create {
public:
month* GetArr();
create();
private:
month arr[12];
month* arrP;
};
create::create(){
month arr[12] = { month(31), month(28), month(31), month(30), month(31), month(30), month(31), month(31), month(30), month(31), month(30), month(31)};
month* arrP = arr;
}
month* create::GetArr()
{
return arrP;
}
您遇到的问题是,您返回了一个指向本地对象的指针,并且该对象在函数结束时立即被销毁,因此指针指向垃圾。
month* year()
{
month* p;
month arr[12] = { month(31), month(28), month(31), month(30), month(31), month(30), month(31), month(31), month(30), month(31), month(30), month(31) };
p = arr;
return p;
}
一旦year()
结束,arr
无效。您要改用的是std::vector
:
std::vector<month> year()
{
std::vector<month> months = { month(31), month(28), month(31), month(30), month(31), month(30), month(31), month(31), month(30), month(31), month(30), month(31) };
return months;
}
现在,您将向所有月份返回一个容器:
struct month
{
month(int d) : days(d) {}
int numberOfDays() const { return days; }
private:
int days;
};
int main()
{
auto months = year();
for (auto m : months)
std::cout << "Days in month: " << m.numberOfDays() << std::endl;
}
你如何恢复记忆没有问题。问题是您返回的指针指向在该函数的局部变量空间中创建的变量(称为其堆栈帧(。当您返回该函数时,该堆栈帧将被"销毁",您将无法再访问它。实际上,它实际上并没有被破坏,这就是为什么您可以访问它的原因(但这非常危险(。要解决此问题,您必须创建一些不在函数堆栈帧内的内存,然后返回指向该内存的指针。
以下是动态内存的一些很好的解释:
更切中要害
更好的解释
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空