Search code examples
c++variable-length-array

Static array of chars with dynamic size


I'm creating static array of chars which size is defined runtime. And I'm not getting compilation errors.
How is this possible?
Here is my example:

void f(const string& val) {
    char valBuf[val.size() + 1]; strcpy(valBuf, val.c_str());
    cout << valBuf << endl;

  }

int main() {
    string str = "aaaa";
    f(str);

    return 0;
}

Solution

  • VLAs (i.e. variable length arrays) are a feature of C99 which some C++ compilers (GCC, for example) support as an extension.

    This is not allowed under standard C++.