Search code examples
c++arraysvariable-length-array

Initialize array with a non-const function argument


Is there any way to initialize an array with a non-const integer, or to make the existing variable constant in order to make it a valid argument?

bool f( const char s[], const int n )
{
    char c[n]; // error: expression must have a constant value
}

Solution

  • No, not in the general case. Use vector<char> c(n) instead.

    Simplified, almost correct explanation: if you don't know what n is at compile time, neither does the compiler. So it cannot put aside memory for the array. This is why vector exists.

    You can always use &c[0] to get the pointer to char if you need it elsewhere.

    But it is possible in C99, apparently. Thanks to @Matt McNabb for pointing this out. If you can wait a few years you might be able to compile it in C++, too. In the meanwhile, use vector.

    If you insist to have an "array" in C++, you would have to do something like:

    char* c = new char[n];
    

    If your program does not run forever, or do this too often, you can even just leave it as it is and not bother deleting. Tools like Valgrind might complain though.