从一个动态分配的数组复制到另一个C ++ [英] Copying from One Dynamically Allocated Array to Another C++

查看:151
本文介绍了从一个动态分配的数组复制到另一个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;
}

这里似乎发生的是 resized [ i] = orig [i] 是通过引用复制值而不是值,因为打印orig在它调整大小后返回一堆垃圾值,除非我注释 delete [] orig 。我如何做一个深的副本从原始大小,或有我面临的其他问题吗?我不想使用std :: vector。

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.

推荐答案

记住,C ++中的参数是通过值传递的。您正在将调整大小指定给传递给您的指针的副本,函数外的指针保持不变。

Remember, parameters in C++ are passed by value. You are assigning resized to a copy of the pointer that was passed to you, the pointer outside the function remains the same.

你应该使用双重间接(或者一个双指针,即指向 int 的指针) p>

You should either use a double indirection (or a "double pointer", i.e. a pointer to a pointer to 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;
}

或指向指针的引用:

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;
}

顺便说一下,对于数组大小,你应该使用 std :: size_t from < cstddef> - 保证保存任何对象的大小,并明确说明我们正在处理对象的大小。

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.

这篇关于从一个动态分配的数组复制到另一个C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆