C++ 在函数中声明动态数组
我正在制作一个函数,如果前一个数组已满,则重新分配一个新的动态数组。但是,如果我编译它,就会发生运行时错误。当我使用Visual Studio 2015对其进行调试时,似乎在函数完成后,编译器无法访问动态数组或数组被删除。你能告诉我为什么吗C++ 在函数中声明动态数组,c++,C++,我正在制作一个函数,如果前一个数组已满,则重新分配一个新的动态数组。但是,如果我编译它,就会发生运行时错误。当我使用Visual Studio 2015对其进行调试时,似乎在函数完成后,编译器无法访问动态数组或数组被删除。你能告诉我为什么吗 void reallocateMemory(string* arr, int& physicalSize, int addedMemory) { string* result = new string[physicalSize + added
void reallocateMemory(string* arr, int& physicalSize, int addedMemory) {
string* result = new string[physicalSize + addedMemory];
for (int i = 0; i < physicalSize; i++) {
result[i] = arr[i];
}
delete[] arr;
arr = result; // After this code, it seems variable arr works well.
result = nullptr;
physicalSize += addedMemory;
} // However, when the function returns, arr cannot access a dynamic array.
void reallocatemory(string*arr、int&physicalSize、int addedMemory){
字符串*结果=新字符串[physicalSize+addedMemory];
对于(int i=0;i
但是,当函数返回时,arr无法访问动态数组
的确如此arr
是一个局部变量,在函数返回后将不再存在。您在函数中分配的内存会泄漏,因为它不再由任何变量指向
您需要某种方法将指针传递到函数范围外新分配的内存。典型的方法是:1)更改函数的返回类型,并返回指针2)将原始指针值作为引用传递,以便函数可以修改引用的指针变量。
arr=result
仅分配给局部变量arr
。调用者没有得到更新的指针。为什么不直接使用std::vector
或其他东西呢?要@user2357112的注释,您需要字符串*&
(指向字符串的指针的引用)。但实际上,请使用std::vector
。