c语言 int --可以到0,为什么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]) == 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),结果相同.在此先感谢您的帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值