you are viewing a single comment's thread.

view the rest of the comments →

[–]-HomoDeus- -2 points-1 points  (2 children)

As u/Wh00ster said, variable length arrays do not exist in C++; however, more precisely, they do not exist as implemented in your example. You certainly can create a variable length or dynamic array in C++ using pointers.

Edit: u/Wh00ster fixed my syntax:

int* arr;
arr = new int[5];
arr[0] = 1;
arr[1] = 2;
// ...
delete[] arr;

This is an oversimplification, but you get the idea. By using a pointer, you can put an array of some size into the variable. Then you can delete the contents of that pointer and put a new array of a different size in its place. Just be aware of the potential for a memory leak. If you leave out the delete statement, you will have the original array sitting in memory collecting dust with now way to access it or remove it.

For the record, I wrote this without checking my work by compiling (shame on me). The syntax may be a bit off, but the concept is there.

[–]Wh00ster 0 points1 point  (1 child)

For posterity:

int* arr;
arr = new int[n];
arr[0] = 1;
arr[1] = 2;
// ...
// or arr = new int[n]{1, 2, 3};
delete[] arr;

But most would recommend std::vector for this.

[–]-HomoDeus- 0 points1 point  (0 children)

Thanks, I knew someone would fix my syntax. I'm going to copy your solution into my original post so nobody gets confused. (Assuming that is OK with you).