I used C in Visual Studio to make a code for a user to input size of array.
The code does not work in Visual Studio and gives errors.
But on a site like replit it works.
I don’t understand what to do to make it work in Visual Studio.
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <math.h>
int main()
{
int m;
do
{
printf("please enter array size--> ");
scanf_s("%d", &m);
} while (m <= 1);
int arry[m];
for (int i = 0 + 1; i < m + 1; i++)
{
printf("%d,", arry[i] = i);
}
return 0;
}
3
Answers
This declaration
is a declaration of a variable length array that is conditionally supported by C compilers because
m
is not an integer constant expression.It seems you are using a version of MS VS the C compiler of which does not support variable length arrays or you need to change properties of your project and select the last version of the C compiler.
Otherwise declare an array of a fixed size that is not less than the possible value of the variable
m
or allocate it dynamically.In any case pay attention to that this for loop
results in accessing memory beyond the array because the valid range of indices is
[0, m)
.It must look like
You can try my sanity check code below to test the usefulness and standard compliance of your compiler:
Compilers giving the output "mighty strange" or "garbage" will not support variable-length arrays, if supporting the C language at all.
Output from various common x86 compilers below.
Default settings
This compiler is modern and useful.
This compiler is modern and useful.
This compiler is modern and useful.
This compiler is modern and useful.
This compiler is garbage.
-std=c99
-std=c99
:This compiler is old but useful.
-std=c99
:This compiler is old but useful.
-std=c99
:This compiler is old but useful.
-std=c99
:This compiler is old but useful.
/std:c99
:This compiler is garbage.
-std=c11
-std=c11
:This compiler is modern and useful.
-std=c11
:This compiler is modern and useful.
-std=c11
:This compiler is modern and useful.
-std=c11
:This compiler is modern and useful.
/std:c11
:This compiler is garbage.
-std=c17
-std=c17
:This compiler is modern and useful.
-std=c17
:This compiler is modern and useful.
-std=c17
:This compiler is modern and useful.
-std=c17
:This compiler is modern and useful.
/std:c17
:This compiler is garbage.
By default, when MSVC compiles code as C, it implements ANSI C89 with Microsoft-specific language extensions. Some of these MSVC extensions are standardized in ISO C99 and later.
__STDC_NO_VLA__
is defined as 1 if the implementation doesn’t support standard variable length arrays. The MSVC implementation defines it as 1 when compiled as C and one of the /std C11 or C17 options is specified.https://clang.llvm.org/c_status.html#c99
https://gcc.gnu.org/c99status.html
MS says VLA is dangerous for you & less efficient so they are not supported