array size initialized dynamically example

88 views Asked by At

I was having trouble understanding why

int n;

cin>>n;
int arr[n];

works. I was told that this code should not run because the value of 'n' could only be declared during runtime and therefore should not compile. I was also told that my 'n' variable should be constant. How do you make it constant when there is a 'cin>>' (Im having trouble understanding how to fit in a constant).I know the code is rather simple, but I'm conflicted because of what I was told.

2

There are 2 answers

0
user4581301 On BEST ANSWER

According to the C++ Standard ([dcl.array])

In a declaration T D where D has the form

D1 [ constant-expressionopt ] attribute-specifier-seqopt

the size of an array must be constant (or not specified with an appropriate initializer).

However some compiler developers have elected to allow Variable Length Arrays (VLA) be it for programmer convenience, to maintain the ability to compile C code in C++ (C has allowed VLA since the C99 Standard), or some nefarious purpose that we may only learn after they have conquered the world.

The best standard compliant solution is to use a std::vector when the size of the allocation cannot be known at compile time.

int n;

if (cin>>n) // don't allocate unless n is valid
{
    vector<int> arr(n);
    // use arr 
}

Even if VLA is available, the vector is still a safer solution. vector is allocated from Dynamic storage, often a much larger data store than Automatic storage, and if the allocation fails an exception is thrown. The behaviour of a Variable Length Array that is too large for storage is often undefined and likely overflows the stack (a common form of Automatic storage), resulting in mystery bugs galore.

Allocating raw memory with new should be avoided as it picks up additional management (it must be manually deleted at some point with delete[]) and book-keeping (the size of the allocation is unknown to the pointer) responsibilities. The programmer may also now have to address The Rules of Three and Five.

0
user8552182 On

People don't use arrays anymore, use a vector or a list, you don't have to worry about sizing them and there is load of useful functions available for processing data in them.