Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Why we generally not make a variable size array.

+1 vote
asked Aug 9, 2020 by Vikas Kumar (150 points)
If we have to make a 'n' size array then we generally write like arr[100] "n<100" and using loop we enter n variable.Instead of making 100 size array why we not make n size array.

1 Answer

+1 vote
answered Aug 12, 2020 by Peter Minarik (86,130 points)
edited Aug 12, 2020 by Peter Minarik

You can create arrays of non-const size

Please, consider the following code:

#include <stdio.h>

int main()
{
    int length;
    printf("How many element would you like to store in the array?\nElement count: ");
    scanf("%d", &length);

    int array[length];
    printf("\nArray declaration of length %d is done...\n", length);
    for (int i = 0; i < length; i++)
        array[i] = i;

    printf("Array is now filled with values...\n");

    return 0;
}

If you run this piece of code, you can see that we can indeed allocate and use an array whose length and size was not known at compile time.

If I recall correctly, in some old version of C this was not supported, hence the restrictions you've seen. The alternative was to allocate/deallocate memory for such arrays (malloc/free). But this is not needed for two decades now or so, unless you force the compiler to use some very old (20+ years) standards.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...