我得到了段错误核心转储。我的函数应该返回输入参数后面的素数,或者如果它是素数则返回该数字。
当我编译时,我没有错误,我也用-Wall
编译,它工作了。但是当我运行该程序时,我收到segmentation failure, core dumped
。我看不到问题所在。
#include <stdio.h>
int ft_next_prime(int nb)
{
int i = 2;
int notPrime = 0;
while (i++ < 9 || notPrime != 1) {
if (nb == i)
i++;
else if (nb % i == 0)
notPrime = 1;
}
return ((notPrime) ? ft_next_prime(nb++) : nb);
}
int main()
{
printf("%d", ft_next_prime(15));
}
为什么?
另外,我可以写这个吗?
while (i++ < 9 || !notPrime)
if (nb % (i != nb) == 0)
notPrime = 1;
最佳答案
使用以下行代替返回语句:
return ((notPrime)? ft_next_prime(nb+1) : nb);
导致段错误的原因有多种。就您而言,堆栈空间不足。
行 ft_next_prime(nb++)
执行并返回 ft_next_prime(nb)
— 具有完全相同的参数 — 然后递增 nb
— 无意义但这正是您告诉它要做的。
关于c - 分段故障核心转储: Function that returns the next prime number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66606118/