我有一个 C++ 中的基本程序,它列出了给定数量的素数。完成工作的类如下 - 我的问题是,当“数量”的输入为 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]) == 0) {
k=1;
}
j++;
} //end the while loop
if (k==0) {
primes[p] = i;
p++;
}
} //end the for loop
} //end the "else" part (this was only necessary in case memory could not be allocated)
return primes;
}
我也尝试不使用(nothrow),结果相同。提前感谢您的帮助!