是否可以在分配内存之前复制动态分配的数组指针
Is it possible to copy a dynamically allocated array pointer prior to memory allocation?
首先,如果之前有人问过这个问题,我深表歉意。我似乎找不到合适的信息。
以下代码并没有像我想象的那样打印"300":
#include <iostream>
int main()
{
int *array;
int *arrayCopy = array;
array = new int[4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;
std::cout << arrayCopy[2];
return 0;
}
但是,如果我移动线
int *arrayCopy = array;
在上面代码中它后面的行下面。为什么?
(附言:我知道内存泄漏,std::vector更好……我只是好奇)。
否,当您执行int *arrayCopy = array;
时,您会在该时刻将array
的值捕获到arrayCopy
中,因此,如果您在复制到arrayCopy
后修改(注意,最初array
指向某个随机位置,您通过执行new
使其指向正确位置)array
,则更改后的值将不会反映回arrayCopy
。
也许您正在考虑使用对指针的引用?以下是您当前代码的情况:
int *array; // Currently points to an undefined (invalid) memory location.
int *arrayCopy = array; // Now this points to the same undefined memory location as array.
array = new int[4]; // Now array points to valid memory, but arrayCopy still points to undefined space.
如果你做了这样的事情,那就不一样了:
int *array; // Points to undefined
int *&arrayCopy = array; // This is a reference to array. That means if you change array, arrayCopy will also reflect the changes.
array = new int[4]; // Now since array points to valid space, arrayCopy does too.
从技术上讲,这并不完全正确,因为不同的事情正在发生。引用本质上是与指针相同级别的间接引用,只是编译器为您执行所有的去引用操作。但我所描述的基本上是它的工作原理。如果你只是把额外的&
放在那里,你的代码就会按照你的想法运行。
int *array; // array is ???
int *arrayCopy = array; // copy is ???
array = new int[4]; // array is valid pointer, copy still ???
此代码片段执行以下操作:
- 创建一个不确定值的
int
指针(可以是任何值) - 将该不确定值复制到副本
- 将原始指针的值更改为指向新创建的数组
换句话说,第三行"断开"两个指针,使副本仍然指向一个不确定的位置。
取消引用指针副本是一种未定义的行为,而不是您想要处理的事情。
相反,如果序列更改为(如您的问题中所述):
int *array; // array is ???
array = new int[4]; // array is valid pointer
int *arrayCopy = array; // copy is now also the valid pointer
则复制指针被设置为原始,在原始被初始化为指向数组之后。没有发生断开,因此array[2]
实际上与arrayCopy[2]
相同。
是否可以在分配内存之前复制动态分配的数组指针?
没有。
然而,你可以这样做:
int *array;
int *&arrayReference = array;
int *array; // points to some random value
int *arrayCopy = array; // points to the same value
array = new int[4]; // array points to a new value, arrayCopy does not
如果你想让一个指针一直指向任何"数组",创建一个双指针
http://computer.howstuffworks.com/c32.htm
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 使用动态分配将 char* 复制到另一个字符**
- C++成功复制动态分配的 obj 而不复制 ctor?
- 复制构造函数继承动态分配的数组
- 如何复制或返回包含动态分配的内存的对象
- 复制动态分配的 2D 数组
- 在班级中使用动态分配的C风格字符串,并带有复制和分配操作员,给出了意外的结果
- 如何将复制构造函数与动态分配一起使用
- 复制构造函数失败..重载,动态分配
- 使用Strcpy_s复制动态分配的字符数组
- 复制构造动态分配对象的问题
- 拆分动态分配的数组,无需线性时间复制
- 将动态分配的阵列复制到更大的阵列,而不会发生内存泄漏
- 复制构造函数对动态分配的作用
- 是否可以在分配内存之前复制动态分配的数组指针
- 复制构造函数和动态分配的数组
- 复制/连接动态分配的C风格字符串
- 是结构体中的复制构造函数,该结构体包含动态分配的数组,总是必需的
- 在复制构造函数中调用动态分配的类的复制构造函数?