can we give the number of elements in an array as needed without using a variable?

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    int L[n];
    // ...
    return 0;
}

I’m asking if I can give the number of elements in an array as needed using a variable . The teacher told us that this method is not recommended and I did not understand why. Thanks for answering for my question .

>Solution :

This declaration

int L[n];

is a declaration of a variable length array. Variable length arrays are conditionally supported by compilers.

So it is not excluded that you can meet a compiler that does not support such declarations.

Pay attention to that in this declaration the value of the variable n shall be greater than 0.

As such an array has automatic storage duration then its size should not be vary big. Otherwise you should allocate memory for the array dynamically.

Leave a Reply