I have this code:
std::string name = "kingfisher";
char node_name[name.size()+1];
strcpy(node_name,name.c_str());
node_name[name.size()] = '\0';
It worked well in DevC++, but in Visual C++, i got a problem named “name.size() must be constant value”! How to solve the problem? I know that i have to use a const value in declaration of node_name, but sometimes (like the case above) i cant! thanks!
As the value of
name.size()is not known at compile time, in the above declaration,node_nameis variable length array (VLA) which is not allowed in ISO C++.In DevC++, it compiles and works, because it provides VLA feature as extension, which is enabled in your compilation configuration.
Use
std::string, orchar *along withnew[]/delete[], whatever suits your need.In your particular case, i.e if you know the string-literal already, then you could write this:
However, if the string value isn’t known and you want to copy it from somewhere, then do this:
Use
std::strncpyinstead ofstd::strcpy, as the former takes the buffer-size also as third argument, as shown above, and the latter doesn’t (which is unsafe usually; not in this case though).