问题描述
我的意图是从已经创建的char[]
的长度创建一个char*
。
我问自己为什么这无效:
void copyStringsV2() {
const char* source = "this is my string.";
const int length = strlen(source);
const char* dest[length];
}
编译器给我这个提示:
Severity Code Description Project File Line Suppression State
Warning C4101 'str_b': unreferenced local variable CStrings
xxx\cstrings.cpp 46
Error C2131 expression did not evaluate to a constant CStrings
xxx\cstrings.cpp 161
Error (active) E0028 expression must have a constant value CStrings
xxx\CStrings.cpp 161
你可以帮我吗?
解决方法
您正在尝试声明一个可变长度数组,which is not a standard feature in C++。定长数组必须在编译时知道其长度。这就是编译器错误所抱怨的。
如果直到运行时为止都不知道长度,则必须动态分配复制的字符串,例如通过new[]
:
void copyStringsV2()
{
const char* source = "this is my string.";
const int length = strlen(source);
char* dest = new char[length+1];
strcpy(dest,source);
...
delete[] dest;
}
或者是std::vector
,因此您无需直接使用new[]
/ delete[]
:
#include <vector>
void copyStringsV2()
{
const char* source = "this is my string.";
const int length = strlen(source);
std::vector<char> dest(length+1);
strcpy(dest.data(),source);
...
}
但是,在这种情况下,最好使用std::string
:
#include <string>
void copyStringsV2()
{
const char* source = "this is my string.";
std::string dest = source;
...
}
,
对于初学者,您应该在此声明中使用类型size_t
而不是类型int
const int length = strlen(source);
^^^
此常数是运行时的常数。因此您可能不能在声明中使用它
const char* dest[length];
因为此处声明为可变长度数组,而可变长度数组(VLA
)不是标准的C ++功能。
也不清楚为什么数组元素的类型是const char *
而不是const char
。
此外,还应初始化一个常量对象。
,我的意图是创建一个
char[]
const char* dest[length];
这不是char数组。那是指向const char的指针数组。
此外,如果希望数组能够适合原始的以null终止的字符串,则必须在数组的长度中包含null终止符,以便其大小为length + 1
。
我问自己为什么这无效:
编译器给我这个提示:
expression did not evaluate to a constant
你可以帮我吗?
数组的大小必须是编译时间常数。 length
不是常数,因此不能用作数组的长度。
在编译时无法通过指向字符串元素的指针来计算字符串的长度。但是,例如,如果使用引用,并且使用constexpr
函数来获取长度,并且使用了constexpr
(const
也可以)变量,则可以使用它作为数组的大小。 C ++标准库中有这样的功能:
auto& source = "this is my string.";
constexpr auto length = std::char_traits<char>::length(source);
char dest[length + 1];
,
为什么这不能编译
因为这是C ++,并且C ++已经提供了各种各样的工具 1 。最好的选择是std::string
。可以复制字符串并传递字符串,而无需编写其他代码。
#include <string>
int main()
{
const std::string source = "this is my string.";
const std::string dest = source;
// do something with dest
}
1)因此,您不需要variable length arrays,它不属于C ++。