我创建了这段代码来解决一些有效的在线答案,但我想知道以这种方式分配动态内存是否可以。数组大小在整个循环中连续定义。可以吗?
#include <iostream>
using namespace std;
int main ()
{
int sum=0;
int x;
int *ptr = new int[x];
ptr[0]=1;
ptr[1]=2;
int max = 4000000;
int i=2;
while (ptr[i-2]<max)
{
ptr[i]=ptr[i-1]+ptr[i-2];
i++;
}
// now we use (i -1) as the last array fill b/c i is bigger than 4 000 000
// sort with val % 2 == 0 !modulus!
for (int j=0; j<(i-1); j++) {
if (ptr[j]%2==0) {
sum+=ptr[j];
}
}
delete[] ptr;
cout<<sum;
return 0;
}
最佳答案
不,这不行,因为int x;
未初始化,可能包含一些垃圾。
编辑。
从评论到这篇文章。
1)使用std::vector<int>
而不是 C 数组。
2) 如果不想使用 vector - 添加计算元素的循环,然后为数组分配内存并使用它。
3) 如果第一种和第二种情况不接近,则使用一些大尺寸的静态数组。
关于c++ - 这是分配非常量数组的合法举动吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11553858/