I'm trying to get this clear up in my mind.
int* arrayA = new int[3];
int arrayB[3] = {1,2,3}
arrayA = arrayB;
Does the value of arrayB
get copied over to arrayA
?
Or does arrayA
become a pointer to arrayB
?
Naked new
is evil, especially for arrays. Use std::vector
if you need dynamic array and std::array
if you need static one.1
Now the actual answer is simple. arrayA
is a pointer. So it's made to point to arrayB
. That has additional effect that:
delete arrayA
will now crash or something else unpleasant, because you would be trying to free unallocated memory.Actually while C++ allows assigning structures and classes, it does not support assigning arrays at all. Unless part of an object either managed as in std::vector
or as array member as in std::array
(note: std::array
is C++11).
1 The main reason is that the containers guarantee the resources will be released in their destructors, so called RAII idiom, avoiding most opportunities for memory leaks and dangling references.
int* arrayA = new int[3];
arrayA now stores the address in memory of a different memory block thats large enough to contain 3 ints which is stored on the heap.
int arrayB[3] = {1,2,3};
arrayB is a block of memory thats large enough to contain 3 ints which is stored on the stack.
arrayA = arrayB;
Copies the address of the memory block that's stored on the stack into the variable arrayA. You have now lost the only reference to memory block stored on the heap, and have no way to free up the memory (a memory leak)
The memory stored on the stack and now pointed to by arrayA will not be safe to access when the current function returns. In particular returning arrayA (or arrayB) is not safe.
For
Does the value of arrayB get copied over to arrayA?
Nope. It will not copy arrayB to arrayA. If you want to do so, you can do like,
for (int i=0;i<3;i++) arrayA[i]=arrayB[i]; //This is two arrays has same value
does arrayA become a pointer to arrayB?
Yes. It become a pointer to array of arrayB. After arrayA = arrayB; statement, memory allocated in the first line can not be accessible and it is a leak.
arrayA=arrayB; result in copying the address of arrayB to arrayA. arrayA will start pointing to the arrayB. Check it using,
printf("\n Base address of A[%u] base address of B[%u]", arrayA, arrayB);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With