Dynamic and static arrays: When both are possible, what's usually the rationale behind using one over the other?
One of the situations might be
int n;
cin >> n;
int a[n];
versus
int n;
cin >> n;
int* a = new int[n];
Dynamic and static arrays: When both are possible, what's usually the rationale behind using one over the other?
One of the situations might be
int n;
cin >> n;
int a[n];
versus
int n;
cin >> n;
int* a = new int[n];
int a[n]
is a variable-length array, which is not allowed by the C++ standard, thus the second code snipper should be your option.
Use -pedantic
flag, and you should get:
warning: ISO C++ forbids variable length array 'a' [-Wvla]
int a[n];
^
As other answers pointed out, you semantics of a variable length array is invalid. However, c++ does support dynamic length arrays via the Vector class, so your question still makes sense, just not with the syntax you used. I am going to interpret the question then as should you use Vectors or arrays. The answer is:
1)Use arrays when you don't need dynamic size or resizing and speed is critical and you are not concerned with the array index being out of bounds.
2)otherwise use vectors