c - 为什么执行此 C 程序时会出现段错误?

标签 c segmentation-fault

当我执行这个程序时,我遇到了段错误,但不知道为什么。 只要它大于 0,它就应该返回输入的阶乘(?)。

#include <stdio.h>

int factorial(int input) 
{
    if (input > 0)
    {
    return input * factorial(input--);
    }
    else
    {
    return 1; 
    }
}
int main()
{
    printf("%d", factorial(23));
    return 0;
}

最佳答案

factorial(input--) 并没有像你想象的那样做。使用阶乘(input-1)

这是一个page that documents the post-decrement operator这应该有助于正确使用它。您永远不必使用它。您始终可以使用 +-=(赋值)执行您想要的操作。

您的程序正在产生段错误,因为正如您所编写的,factorial(23) 调用 factorial(23),导致 stack overflow .

关于c - 为什么执行此 C 程序时会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28010513/

相关文章:

c++ - 信号 : Segmentation fault (11) when using Openmpi

c - 使用函数指针时出现段错误

编译器想要 ";"- 我不知道为什么(在 C 中)

android - Android 7 中的 IPerf3 执行不起作用

c - 为什么编译器会抛出这个警告 : "missing initializer"? Is the structure initialized?

c - 使文件可执行

c++ - 在 .c 文件中使用 Linux 中的 msgget 创建消息队列接收函数未实现错误

c++ - 深度优先图遍历

c - 我无法理解这个段错误

c - C 中的函数指针及其行为