According to the Arrays section in Ultimate C++ Part 2: Intermediate course I am told I can’t assign one array to another because the array name is essentially a hexadecimal number (Pointer), which is the address of the array in memory. However, when I use the unpacking technique, I am able to use the array name to assign its elements to separate int variables. Why is that?
I believe the part you are referring to Mosh is telling you that assigning one array to another is not going to create a copy of that array. You will just have two variables that point to the same array.
int a[2] = {1, 2};
int b[2] = a;
If we do that, the two variables point to the same array. We can copy the array instead:
int b[2];
copy(begin(a), end(a), begin(b));
Now the two variables point to separate arrays which have the same elements.
In contrast, unpacking is just syntactic sugar to simplify a common operation. If the number of elements in an array is small and known you can use the unpacking technique to copy the elements of the array into individual variables. I think this actually uses an array copy operation under the surface, but either way the syntax gets you a copy of the value.
auto [x, y] = a;
Now x
has the value 1, y
has the value 2, and both are completely disconnected from a
.
You can even use a special unpacking syntax to bind the variable as a pointer which is equivalent to the one that the array elements are pointing to (so updating the array value updates the same element the variable pointer is pointing to).
auto& [px, py] = a;
Now px
is a pointer to a[0]
and py
is a pointer to a[1]
. Changes to the array will update the values pointed to by the pointers:
a[0] = 3;
// *px == 3
Thank you for the reply. But why doesn’t work with int variable instead of auto?