小编use*_*713的帖子

为什么int数组在C++中没有初始化为零?

我有一个C++基本程序,它列出了给定数量的素数.完成工作的类是下面的 - 我的问题是,当"amount"的输入为10(特别是10 - 它适用于我尝试过的所有其他数字)时,下面生成的数组未初始化为一个零的数组.因此,"数组的最后一个元素为空"返回false,并且我的代码无法正常运行.

我不知道我是否误解了,但不应该将int数组初始化为零?如果没有,整数10有什么特别之处,导致它初始化为奇怪的值?

int* primecalc(int amount) {

int* primes = new (nothrow) int [amount];

//Throw an error if we can't allocated enough memory for the array.
if (primes==0) {
cout<< "Error allocating memory.";
return 0;
}

//Otherwise, start iterating through the numbers.
else {
primes[0] = 2;
primes[1] = 3;

int p = 2;

for (int i=4;primes[amount]==0;i++) {
int j = 0;
int k = 0;

    while ((primes[j]<=floor(i/2)) && !(primes[j]==0) && (k==0)) {

        if ((i % primes[j]) …
Run Code Online (Sandbox Code Playgroud)

c++ arrays initialization

4
推荐指数
1
解决办法
3867
查看次数

标签 统计

arrays ×1

c++ ×1

initialization ×1