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.
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.