1

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];
9
  • 6
    Well, int a[n] is an error in C++. Commented Oct 22, 2017 at 18:26
  • int a[n] is called variable length arrays, and is invalid, don't write them. Commented Oct 22, 2017 at 18:32
  • @melpomene, I can compile and run this without an error. Commented Oct 22, 2017 at 18:34
  • @HuXinqiao That's because compilers typically support not only standard C++, but also certain language extensions. When passed the right compiler flags (-pedantic/-pedantic-errors with GCC), such extensions will be warned about. Commented Oct 22, 2017 at 18:35
  • @HuXinqiao You're probably using gcc without warnings enabled. Commented Oct 22, 2017 at 18:38

2 Answers 2

1

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];
            ^
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.