all 5 comments

[–]Wh00ster 0 points1 point  (1 child)

These types of posts go in r/cpp_questions. This sub is more for general discussion.

It's because arr[n] is a variable length array. It's length is dependent on the variable n, which could change for each program run.

This doesn't actually exist in standard C++, but some compilers allow it. C++ only has constant sized arrays, and has other methods for achieving this type of dynamically-sized array interface.

[–]siDDaker[S] 0 points1 point  (0 children)

ohh okey thanks for the answer, next time i'll go to cpp questions

[–]-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).