Question

I wrote a program, where the size of an array is taken as an input from user.

#include <stdio.h>
main()
{
    int x;
    scanf("%d", &x);
    int y[x];
    /* some stuff */
}

This program failed to compile on my school's compiler Turbo C (an antique compiler). But when I tried this on my PC with GNU CC, it compiled successfully.

So my question is, is this a valid C program? Can I set the size of the array using a user's input?

Was it helpful?

Solution 3

c90 does not support variable length arrays you can see this using this command line:

gcc -std=c90 -pedantic code.c

you will see an error message like this:

warning: ISO C90 forbids variable length array ‘y’ [-Wvla]

but c99 this is perfectly valid:

gcc -std=c99 -pedantic code.c

OTHER TIPS

It is a valid C program now, but it wasn't 15 years ago.

Either way, it's a buggy C program because x is used without any knowledge of how large it might be. The user can input a malicious value for x and cause the program to crash or worse.

C99 gives C programmers the ability to use variable length arrays,which are arrays whose sizes are not known until run time. --C:A Reference Manual

Instead of asking whether this is strictly valid C code, it may be better to ask whether it is good C code. Although it is valid, as you have seen, a number of compilers do not support variable length arrays.

Variable length arrays are not supported by a number of modern compilers. These include Microsoft Visual Studio and some versions of the IBM XL compilers. As you have found, variable length arrays are not entirely portable. That's fine if the code will only be used on systems that support the feature but not if it has to be run on other systems. Instead, it may be better to allocate the array with constant size using a reasonable limit or use a malloc and free to create the array in portable manner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top