Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading