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];
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Hu Xinqiao
  • 21
  • 5
  • 6
    Well, `int a[n]` is an error in C++. – melpomene Oct 22 '17 at 18:26
  • `int a[n]` is called variable length arrays, and is invalid, don't write them. – Passer By Oct 22 '17 at 18:32
  • @melpomene, I can compile and run [this](https://pastebin.com/tW5KkNSC) without an error. – Hu Xinqiao Oct 22 '17 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. –  Oct 22 '17 at 18:35
  • @HuXinqiao You're probably using gcc without warnings enabled. – melpomene Oct 22 '17 at 18:38
  • @melpomene that's not the case, see my answer. `Wall` and `Wextra` didn't trigger the message. – gsamaras Oct 22 '17 at 18:40
  • @melpomene, hvd I see. My follow-up would be why is VLA undesirable, and I'll refer to the discussion [here](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). Appreciate the help. – Hu Xinqiao Oct 22 '17 at 18:43
  • It is a good idea to use the flag `-pedantic-errors` to force the compiler to adhere to whatever standard you have configured it to use. – Galik Oct 22 '17 at 18:44
  • @gsamaras Oh, yeah. `-pedantic` (or `-Wpedantic` nowadays) is part of my standard flag set because it enables diagnostics required by the standard. – melpomene Oct 22 '17 at 18:44

2 Answers2

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];
            ^
gsamaras
  • 71,951
  • 46
  • 188
  • 305
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

chessprogrammer
  • 768
  • 4
  • 15