简体   繁体   中英

Expression does not evaluate to constant

I have the following stupid snippet:

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    const string classpath = "Hello Dolly!";
    const int len = classpath.length()+1;
    char str[len];
    strncpy(str, classpath.c_str(), len);
    cout << str << endl;
    return 0;
}

The aim ist to assign a c++ string to ac char array. The string is known at compile time, hence a constant. But the string may vary from one project to an other. I have no intention to count chars for the compiler. Hence the const len should be computed at compile time as shown. This works with cygwin and on linux. But the visualstudio compiler sees a problem and gives me the error C2131! How to work around? (Please consider I'm a Java programmer being troubled loosing time on such kind of problems!)

In C++ array sizes must be known at compile time.

You can dynamically allocate contiguous memory during run-time by using operator new :

char * my_array = new char[length];

Remember to use the delete[] to free up the memory after you are finished with it.

Also, C-style arrays need that terminating nul character so you will need to allocate one extra slot in the array.

To copy a std::string to a character array:

const std::string example = "example";
const std::string::size_type length = example.length();
char * p_array = new char [length + 1];
strcpy(p_array, example.c_str());
cout << p_array << endl;
delete[] p_array;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM