Initialising an array with a variable

I know that initialising an array with a variable is typically impossible, but oddly enough I've found a way which sort of makes it work. Here I've written code that is supposed to create an array and add up the sum of it's elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;


int arraysum(int n)
{   int a[n+1], s=0;
    for (int i=1; i<=n; i++) {
        cin >> a[i];
        s=s+a[i];
    }
    return s;
}

int main () {
    int n, result;
    cin >> n;
    result=arraysum(n);
    cout << result;
    return 0;
}


As seen here, I can initialise a[n+1] as long as it is in a function. Why is that? Is it only specific to the compiler or platform that I use?
Last edited on
You are using a language extension known as Variable Length Arrays. They are mildly evil due to how quickly they can use up the stack, and importantly, they are not standard. So yes, depending on which compiler you use and what options you use with that compiler, this code will not compile.

-Albatross
Thank you! I assume that a standard alternative to what I've written would be using the vector library to do the same thing?
Yes. Using a vector you don't need to know in advance how many elements there are going to be.

You could ask in advance like here how many numbers, or just loop until a sentinel value found or loop until an error obtaining the number etc.
The std::vector is the preferred way.

Also possible, though more error-prone, is to dynamically allocate the array using new. The main thing to remember when using this method is to call delete[] on the array when you are done using it.

But the std::vector alternative is a much better option.
OK, thank you all!
Topic archived. No new replies allowed.