我在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]) == 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),结果相同.在此先感谢您的帮助!