从一个动态分配的数组复制到另一个 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8056746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copying from One Dynamically Allocated Array to Another C++
提问by Rahul Gupta-Iwasaki
This seems like it should have a super easy solution, but I just can't figure it out. I am simply creating a resized array and trying to copy all the original values over, and then finally deleting the old array to free the memory.
这似乎应该有一个超级简单的解决方案,但我就是想不通。我只是创建一个调整大小的数组并尝试复制所有原始值,然后最后删除旧数组以释放内存。
void ResizeArray(int *orig, int size) {
int *resized = new int[size * 2];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
What seems to be happening here is that resized[i] = orig[i]
is copying values by reference rather than value, as printing orig after it gets resized returns a bunch of junk values unless I comment out delete [] orig
. How can I make a deep copy from orig to resized, or is there some other problem that I am facing? I do not want to use std::vector.
这里似乎发生的是resized[i] = orig[i]
通过引用而不是值复制值,因为在调整大小后打印原稿会返回一堆垃圾值,除非我注释掉delete [] orig
. 如何从 orig 进行深层复制以调整大小,或者我面临其他一些问题?我不想使用 std::vector。
回答by Matteo Italia
Remember, parameters in C++ are passed by value. You are assigning resized
to a copyof the pointer that was passed to you, the pointer outside the function remains the same.
请记住,C++ 中的参数是按值传递的。您正在分配传递给您的指针resized
的副本,函数外的指针保持不变。
You should either use a double indirection (or a "double pointer", i.e. a pointer to a pointer to int
):
您应该使用双间接寻址(或“双指针”,即指向指向的指针int
):
void ResizeArray(int **orig, int size) {
int *resized = new int[size * 2];
for (int i = 0; i < size; i ++)
resized[i] = (*orig)[i];
delete [] *orig;
*orig = resized;
}
or a reference to the pointer:
或对指针的引用:
void ResizeArray(int *&orig, int size) {
int *resized = new int[size * 2];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
By the way, for array sizes you should use the type std::size_t
from <cstddef>
- it is guaranteed to hold the size for any object and makes clear that we are dealing with the size of an object.
顺便说一下,对于数组大小,您应该使用std::size_t
from类型<cstddef>
- 它保证保存任何对象的大小,并明确我们正在处理对象的大小。
回答by Thomas Matthews
I highly suggest replacing the arrays with std::vector<int>
. This data structure will resize as needed and the resizing has already been tested.
我强烈建议用std::vector<int>
. 此数据结构将根据需要调整大小,并且调整大小已经过测试。
回答by Drew
orig
must be a pointer to a pointer to assign it to resized
:
orig
必须是指向要分配给的指针的指针resized
:
int **orig;
*orig = resized;