我有一個C++的基本程序,它列出了給定數量的素數。做這個工作的類是下面的 - 我的問題是,當「金額」的輸入是10(特別是10 - 對我嘗試過的所有其他數字都能正常工作)時,下面生成的數組不會被初始化爲一個零數組。因此,「數組的最後一個元素爲空」返回false,並且我的代碼無法正常運行。爲什麼int數組在C++中未初始化爲零?
我不知道我是否誤解了,但不應該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),具有相同的結果。預先感謝任何幫助!
爲什麼你期待新的數組初始化? – YePhIcK 2012-08-04 23:17:53
請注意'primes [amount] == 0'調用未定義的行爲。到primes的有效索引是0到'amount-1'。 – 2012-08-04 23:21:12
@DanielFischer啊,是的,我也應該解決這個問題。謝謝! – user1576713 2012-08-05 09:29:48