我的意图是用我已经创建的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
xxxcstrings.cpp 46
Error C2131 expression did not evaluate to a constant CStrings
xxxcstrings.cpp 161
Error (active) E0028 expression must have a constant value CStrings
xxxCStrings.cpp 161
你能在这里帮我吗?
您正试图声明一个可变长度数组,这不是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];
这不是一个字符数组。这是一个指向const char的指针数组。
此外,如果希望数组能够适应原始的空终止符字符串,则必须在数组的长度中包含空终止符,以便其大小为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(所以您不需要可变长度的数组,它们不是C++的一部分。