can size of array be determined at run time in c? can size of array be determined at run time in c? arrays arrays

can size of array be determined at run time in c?


Array sizes need to be known with ANSI 89 C. The 99 version of the spec removed this limitation and allowed for variable sized arrays.

Here is the documentation no the GNU version of this feature


Variable Length Arrays have been part of C language since C99.But they have been made as an optional feature in C11 - meaning a C11 conforming implementation need not provide it (although, practically all the implementation that support C99 certainly provide VLAs in C11).

You can check if you implementation does not provide VLAs using the macro __STDC_NO_VLA__ (If it's defined in C99 or C11 mode of compilation, then your implementation doesn't support VLAs).

So deciding an array size at runtime is possible in modern C (>= C99) and code like the below is fine:

int s;printf("Enter the array size: ");scanf("%d", &s);int a[s];

One obvious drawback of VLAs is that if s is quite big and the allocation of a could fail. Worse, there's no way to check if the allocation has failed and you'll run into runtime errors (e.g., segfault). It's essentially undefined behaviour. So you want to avoid VLAs if the array size is too big. Basically, when in doubt, go for dynamic memory allocation (see below).

Another issue, much less severe compared to other, with VLAs is that they have automatic storage duration (aka "stack allocated"). So if you want something that lasts for longer duration then the block scope where the VLA is declared, then VLAs are of no help.

Also relevant is that there's no VLA in C89,. So using the dynamic memory allocation is the only way. Although, there were some non-standard extensions such as alloca() which is similar to VLA and has the same drawbacks as VLAs).

int s;printf("enter the array size: ");scanf("%d",&s);int *a = malloc(s * sizeof *a);...free(a);


If you need to allocate an array with dynamic size, you have to get it from the heap, with malloc().

int *a = malloc(sizeof(int) * s)