Search code examples
arrayscfibonacci

Declaring Array in C with variable length


This block of code gives me the fibonacci numbers

#include <stdio.h>

int main()
{
    int n; //integer overflow error for n > 47

    printf("How many Fibonacci numbers?\n");
    scanf("%d", &n);

    int fibs[n];

    fibs[0] = 0;
    fibs[1] = 1;

    printf("%d ", fibs[0]);
    printf("%d ", fibs[1]);

    for(int i = 2; i < n; i++)
    {
        fibs[i] = fibs[i - 2] + fibs[i - 1];
        printf("%d ", fibs[i]);
    }
    return 0;
    //gives 0 1 1 2 3 5 8 13 21 34 for n = 10

}

But this gives me the wrong output but no errors

#include <stdio.h>

int main()
{
    int n, fibs[n];//change

    printf("How many Fibonacci numbers?\n");
    scanf("%d", &n);

    fibs[0] = 0;
    fibs[1] = 1;

    printf("%d ", fibs[0]);
    printf("%d ", fibs[1]);

    for(int i = 2; i < n; i++)
    {
        fibs[i] = fibs[i - 2] + fibs[i - 1];
        printf("%d ", fibs[i]);
    }
    return 0;
    //gives 0 1 for n = 10
}

I know it definitely has something to do with the array and its size not being defined but I'm having trouble understanding what exactly is the problem.

Could someone explain what is going on here?


Solution

  • int n, fibs[n]; attempts to define an array using n for the length, but n has not been initialized, so its value is not determined. Common consequences include:

    • The definition behaves as if n has some small value, possibly zero, and then the following code attempts to store values in the array but overruns the memory reserved for it and thus destroys other data needed by the program.
    • The definition behaves as if n has some large value, causing the stack to overflow and the program to be terminated.

    For example, storing 0 to to fibs[0] or 1 to fibs[1] might write to the memory reserved for n. Then the for loop terminates without executing any iterations because the test i < n is false.