[英]Copying from One Dynamically Allocated Array to Another C++
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
. 这里似乎发生的是
resized[i] = orig[i]
是通过引用而不是值复制值,因为在调整大小后打印orig会返回一堆垃圾值,除非我注释掉delete [] orig
。 How can I make a deep copy from orig to resized, or is there some other problem that I am facing? 如何从orig复制大小,或者是否还有其他问题? I do not want to use std::vector.
我不想使用std :: vector。
Remember, parameters in C++ are passed by value. 请记住,C ++中的参数是按值传递的。 You are assigning
resized
to a copy of the pointer that was passed to you, the pointer outside the function remains the same. 您将
resized
分配给传递给您的指针的副本 ,函数外部的指针保持不变。
You should either use a double indirection (or a "double pointer", ie 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. 顺便说一下,对于数组大小,你应该使用
<cstddef>
的类型std::size_t
- 它保证保持任何对象的大小,并清楚地表明我们正在处理对象的大小。
I highly suggest replacing the arrays with std::vector<int>
. 我强烈建议用
std::vector<int>
替换数组。 This data structure will resize as needed and the resizing has already been tested. 此数据结构将根据需要调整大小,并且已调整大小调整。
orig
must be a pointer to a pointer to assign it to resized
: orig
必须是一个指向指针的指针,以指定它resized
:
int **orig;
*orig = resized;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.