为什么我会收到错误"Segmentation fault(core dumped)"?

nie*_*els 1 c

我刚刚开始使用C编程,我正在制作一个计算特定数量Fibonacci数的程序.它工作正常,除了我收到错误"Segmentation fault(core dumped)".我的代码出了什么问题?

#include <stdio.h>

int main() {
    int max;
    long long int fiNum[] = {1, 1};

    printf("How many numbers do you want to get? ");
    scanf("%d", &max);

    int i = 1;
    long long int x;

    while ( i < max ) {
        x = fiNum[i] + fiNum[i-1];
        printf("%lld ", x);
        i++;
        fiNum[i] = x;
    }

    printf("\nDone!\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我要求让10个数字输出时:

2 3 5 8 13 21 34 55 89 
Done!
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

我正在使用Linux(Ubuntu)顺便说一句.

提前致谢.

Uch*_*chi 5

您将越界访问fileNum仅分配了2个元素的静态数组.

因此,你是未定义行为的受害者.任何事情都可能发生,但在你的情况下,它最终会崩溃.

如果要存储生成的斐波那契数,那么在从用户获得输入后更好地动态分配数组.