Array questions

Hi! When I deal with some build-in arrays, it is said that they can't be copied or assigned. I have looked through some articles, they said that array names were treated as constant pointers - *const, which means these addresses are not modifiable lvalues during their lifetime. Is this explanation correct? Meanwhile, are arrays' memory allocations consecutive? Or can system allocate fragmentary memories to initialize arrays? If so, does system stop us from copying or assigning arrays to prevent memory block override or loss?

1
2
int a1[10], a2[10];
a1 = a2;            //error 
Last edited on
1. The explanation is correct
2. Array memory locations are consecutive. The entire array will be allocated at once as one memory fragment.

I suggest that you don't use C-style arrays, use std::vector instead.
okay, thanks.
It's not entirely correct. An array is not a pointer. It's just that it decays to a pointer to the first element in the array in many situations, which means you can use it almost as if it was a const pointer, but not in all situations (e.g. when using sizeof, or when passing an array by reference to a function).

Array elements are consecutive in memory, as seen by your program. Exactly how it's stored on the hardware is nothing you have control over. The memory could be split up over multiple regions in physical memory but thanks to virtual memory it's nothing you need to worry about.

https://en.wikipedia.org/wiki/Virtual_memory
Last edited on
Peter87's explanation is more precise than mine.
Got it, thanks.
Last edited on
Topic archived. No new replies allowed.