'Expression does not evaluate to a constant

I've just started to learn C++ and I don't understand this error:

std::string AFunction(const std::string& str) {
    size_t s = str.length();

    char inProgress[s];


    return std::string();
}

I get the error:

error C2131: expression does not evaluate to a constant

Here: char inProgress[s];

What do I have to do the set inProgress size with the length of str?

c++


Solution 1:[1]

The problem is that in standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program:

size_t s = str.length();
char inProgress[s]; //not standard C++ because s is not a constant expression

Better would be to use std::vector as shown below:

std::string AFunction(const std::string& str) {
    size_t s = str.length();

    std::vector<char> inProgress(s); //create vector of size `s`


    return std::string{};
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoop Rana