我有这个代码:
std::string name = "kingfisher";
char node_name[name.size()+1];
strcpy(node_name,name.c_str());
node_name[name.size()] = '\0';
它在 DevC++ 中运行良好,但在 Visual C++ 中,我遇到了一个名为“name.size() must be constant value”的问题!如何解决问题?我知道我必须在 node_name
的声明中使用 const 值,但有时(如上例)我不能!谢谢!
最佳答案
char node_name[name.size()+1];
作为name.size()
的值在编译时不知道,在上面的声明中,node_name
是可变长度数组 (VLA),这在 ISO C++ 中是不允许的。
在 DevC++ 中,它可以编译并运行,因为它提供了 VLA 功能作为扩展,该功能在您的编译配置中启用。
使用 std::string
, 或 char *
连同 new[]/delete[]
,无论您需要什么。
在您的特定情况下,即如果您已经知道字符串文字,那么您可以这样写:
char node_name[] = "kingfisher"; //this works great!
但是,如果字符串值未知并且您想从某处复制它,则执行以下操作:
char *node_name = new char[name.size()+1];
std::strncpy(node_name, name.c_str(), name.size()+1); //use strncpy
//work with node_name
//must deallocate the memory
delete []node_name; //not `delete node_name;`
使用 std::strncpy
而不是 std::strcpy
,因为前者也将缓冲区大小作为第三个参数,如上所示,而后者则没有(这通常是不安全的;但在这种情况下不是)。
关于c++ - 在 Visual C++ 中必须具有 const 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11026911/