Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size not static?

Tags:

c++

arrays

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.

like image 488
user1729535 Avatar asked Oct 08 '12 17:10

user1729535


People also ask

Is array size static?

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.

How do you change the size of an array that is static?

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.

Is std :: array fixed size?

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.


1 Answers

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.

like image 186
juanchopanza Avatar answered Oct 16 '22 04:10

juanchopanza