can someone please explain to me why this works. I thought arrays were static and couldn't expand, this piece of code defies my prior knowledge.
#include <iostream>
using namespace std;
int main(){
int test[10];
int e = 14;
for(int i = 0; i < e; i++){
test[i] = i;
cout << " " << test[i];
}
return 0;
}
This code outputs this: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
So basically this program uses array spaces that shouldn't exist. Tried setting 'e' as 15, doesn't work.
Static arrays have their size or length determined when the array is created and/or allocated. For this reason, they may also be referred to as fixed-length arrays or fixed arrays. Array values may be specified when the array is defined, or the array size may be defined without specifying array contents.
If you need to be resizing arrays, then use an ArrayList. Here's an example: ArrayList list = new ArrayList<Object>(); list. add(obj); Object obj2 = list.
std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.
The array's size is fixed, it is not expanding, and going beyond its bounds is undefined behaviour. What you observed is one possible outcome of undefined behaviour (UB). You were unlucky that in this case the UB suggests a pattern consistent with the array expanding.
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