返回指向对象数组的指针

returning a pointer to an array of objects

本文关键字:指针 数组 对象 返回      更新时间:2023-10-16

我在返回指向对象数组的指针时遇到问题,特别是如何定义返回类型,我只是无法获得返回的指针......

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

你如何恢复记忆没有问题。问题是您返回的指针指向在该函数的局部变量空间中创建的变量(称为其堆栈帧(。当您返回该函数时,该堆栈帧将被"销毁",您将无法再访问它。实际上,它实际上并没有被破坏,这就是为什么您可以访问它的原因(但这非常危险(。要解决此问题,您必须创建一些不在函数堆栈帧内的内存,然后返回指向该内存的指针。

以下是动态内存的一些很好的解释:

更切中要害

更好的解释