在第二个数组进行一些更改后,我有两个
数组我想让
第一个数组与第二个数组相同,
是否可以不逐个复制整个数组,
但是通过一个命令以某种方式使第一个数组指向
第二个数组的元素。
2 回答
No, an array is an object and on object is some region of storage. Two arrays are two separate regions of storage.
However, given a pointer to the first element of an array, you can use it to index the array just as you would with the array itself:
int arr[] = {1, 2, 3, 4, 5};
int* p = arr;
arr[2] == p[2];
I don't want to fuel the misconception that arrays and pointers are similar in any way, however. The first line defines an array object containing 5 int
s. The second line defines a pointer that points to the first element in that array.
The reason they can both be used in the same way in the last line is because the name of the array, arr
, is implicitly converted to a pointer to its first element before doing the indexing. So really those two sub-expressions are the same thing. arr[2]
just involves an implicit conversion to a pointer before applying the indexing operator.
Alternatively, you can take a reference to an array:
int arr[] = {1, 2, 3, 4, 5};
int (&r)[5] = arr;
arr[2] == r[2];
Now r
is just an alias for the array. Both arr
and r
literally refer to the array object.
If you want to copy one element at a time, a simple for
loop will do. If you want to copy all elements you could use e.g. memcpy
(if, and only if your arrays have POD types).
Then there's of course std::copy
:
int array1[5] = { ... };
int array2[5];
// Copy from `array1` to `array2`
std::copy(std::begin(array1), std::end(array1), std::begin(array2));