gpt4 book ai didi

c++ - 如何删除在另一个函数中初始化的动态分配的数组?

转载 作者:行者123 更新时间:2023-12-01 14:54:31 24 4
gpt4 key购买 nike

int* generateArray(int size)

该函数应动态创建一个数组,并将创建的数组返回到主程序中生成的数组。
int main() 

{

int *numList = generateArray(501);
cout << "Mode = " << findMode(arr, 501) << endl;

cout << "Median = " << findMedian(arr, 501);

delete[] numList;
numList = nullptr;

return 0;
}

我还需要删除动态分配的数组。我想确定是否正确删除了新指针。通过删除int main末尾的generate,是否也将删除函数中的新指针?
int *generateArray(int size) 

{

srand(time(0));

int *arr = new int[size];

for (int i=0; i<size; i++)
{
arr[i] = rand() % 91 + 10;
}
return arr;
}

最佳答案

How do I delete a dynamically allocated array that is initialized in another function?



理想情况下,您将返回拥有该数组的RAII容器,并负责在其自己的析构函数中销毁该数组。例如 std::vectorstd::unique_ptr<T[]>

如果RAII不是一种选择,例如跨语言API,则在需要分配时,惯例是为资源的创建和销毁提供命名函数:
int* generateArray(int size); // maybe calls new[]
void destroyArray(int*); // maybe calls delete[]

这使API的用户不必依赖分配细节。

By deleting the generated in the at the end of int main would it delete the new pointer in the function as well?



到那时该函数已经返回。该函数的所有局部变量均已销毁。 “函数中的指针”不再存在。 main函数中的指针是该指针的副本:它具有相同的值。

删除一个指针会破坏指向的对象(或数组),并释放内存。如果存在对该对象(或数组)的任何其他指针或引用,则这些其他指针将变为无效。这些其他指针不需要删除,实际上,尝试删除将导致未定义的行为。

关于c++ - 如何删除在另一个函数中初始化的动态分配的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com