是否可以在分配内存之前复制动态分配的数组指针

Is it possible to copy a dynamically allocated array pointer prior to memory allocation?

本文关键字:动态分配 复制 数组 指针 分配 内存 是否      更新时间:2023-10-16

首先,如果之前有人问过这个问题,我深表歉意。我似乎找不到合适的信息。

以下代码并没有像我想象的那样打印"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