我需要在两个不同的函数中访问动态数组.在一个中进行的更改需要转移到另一个.
这些是功能:
void populate(int size, int *ptr)
{
ptr = new int[size];
for (int i = 0; i < size; i++)
{
ptr[i] = rand() % 51;
}
}
void display(int size, int *ptr)
{
for (int i=0; i < size; i++)
{
cout << ptr[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
它在主要被称为
int* ptr = NULL;
Run Code Online (Sandbox Code Playgroud)
在populate
,您试图将指向传递给函数的指针指向动态分配的数组.但是你按值传递指针.这对调用方没有影响,导致内存泄漏.您需要通过引用传递指针:
void populate(int size, int*& ptr)
^
Run Code Online (Sandbox Code Playgroud)
还是退货
int* populate(int size)
{
int* ptr = new int[size];
....
return ptr;
}
Run Code Online (Sandbox Code Playgroud)
但最简单和最安全的做法是使用std::vector<int>
两个函数代替.例如
std::vector<int> populate(size_t size)
{
std::vector<int> v(size);
for (auto& i : v)
{
i = rand() % 51;
}
return v;
}
void display(const std::vector<int>& v)
{
for (auto i : v)
{
std::cout << ptr[i] << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,很明显返回了什么,并且调用者不必阅读他们是否必须管理原始指针所指向的资源.
请注意,populate
可以通过一个电话来替代std::generate
,并display
通过一个呼叫std::copy
.