C++中的动态数组与Java相比
最近,在学习Java后,我开始学习C ++,并被指示制作一个动态数组,因此我尝试制作一个临时变量,其中包含我需要的内容,然后将其重新分配到我真正想要使用的变量中。
void Pile::grow(Stone s){
Stone temp[getLength() + 1];
for (int i = 0; i < sizeof(temp) / sizeof(temp[0]); ++i) {
if (sizeof(temp) / sizeof(temp[0]) < 28){
temp[i] = stoneArr[i];
}
}
stoneArr = temp;
}
但是,由于某种原因,我无法理解的是,编译器给我一个无法重新分配的错误。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在任何地方都不会使用
s
。您是否应该将其添加到您要创建的新数组中?这在标准C ++中是不合法的。固定阵列的大小必须在编译时已知。
一些编译器将“可变长度数组”作为非标准扩展名支持,但是如果您需要编写便携式代码,请不要依靠它们。请参阅为什么不是c ++标准的变量length阵列的一部分?
在运行时动态分配数组,使用
new []
运算符,例如:或者,使用标准
std :: vector
容器,例如:您不能在动态上使用此
size> sizeof
trick数组,更不用说VLA了。sizeof
仅在编译时而不是在运行时评估。由于您正在从现有数组中复制值,因此请使用该数组的长度:
硬编码
28
这里没有意义。实际上,如果检查需要完全删除。当
temp
是VLA时,此分配将无法使用。stonearr
无论如何都不能成为VLA。stonearr
需要是Stone*
指针new []
'D Array(通过遵循 3/5/0 ),或std :: vector :: vector&lt; stone&gt;
(首选)。同样,请尝试尝试:
或:
You are not using
s
anywhere. Are you supposed to add it to the new array you are trying to create?This is not legal in standard C++. The size of a fixed array must be known at compile time.
Some compilers support "variable length arrays" as a non-standard extension, but do not rely on them if you need to write portable code. See Why aren't variable-length arrays part of the C++ standard?
To allocate an array dynamically at runtime, use the
new[]
operator instead, eg:Or, use the standard
std::vector
container instead, eg:You cannot use this
sizeof
trick on a dynamic array, let alone a VLA.sizeof
is evaluated only at compile time, not at runtime.Since you are copying values from an existing array, use the length of that array instead:
Hard-coding a
28
here makes no sense. In fact, this wholeif
check needs to be removed completely.This assignment will not work when
temp
is a VLA. AndstoneArr
can't be a VLA anyway.stoneArr
needs to be either aStone*
pointer to anew[]
'd array (that is managed by following the Rule of 3/5/0), or astd::vector<Stone>
(preferred).With all of that said, try this instead:
Or: