[英]Defining 2D array in C++
As per my understanding, we need to define a constant row and a constant column size for a 2d array in c++ unless we are dynamically allocating it.根据我的理解,除非我们动态分配它,否则我们需要在 C++ 中为二维数组定义一个常量行和一个常量列大小。
I tried this piece of code and it worked without any errors.我试过这段代码,它没有任何错误。
std::vector<std::string> strs;
for(int i ; i < 10; ++i)
{
strs.push_back("This is a test"+ std::to_string(i));
}
int length = 0;
for(int i ; i < 10; ++i)
{
if(strs[i].size() > length)
length = strs[i].size();
}
char c[20][length + 1];
for(int i ; i < 20; ++i)
{
memcpy(c[i], "Test", 5);
cout << c[i] << endl;
}
Could someone please explain how come defining a 2D character array with variable length is possible here?有人可以解释一下如何在这里定义可变长度的二维字符数组吗?
Thanks K谢谢K
char c[20][length + 1];
is not legal C++ if length
is not a compile time constant.如果length
不是编译时常量,则 C++ 不合法。 Some compilers, such as g++, allow it as an extension.某些编译器,例如 g++,允许将其作为扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.