So I have C programing homework and what I suppose to do is get a input from user and make that input length of an array. I basically thought that would work:
int main()
{
int a, b;
int array[a];
scanf("%d", &a);
array[0] = 0;
printf("%d", array[0]);
return 0;
}
It worked on an online compiler but it doesn’t work on my Visual Studio Community IDE.
What is the problem? Is it my code or IDE?
3
Answers
Apart from the fact that
a
is uninitialized at the time it’s first used (which means it will contain garbage bytes – the compiler should tell you if you enable warnings), no, you can’t really do this in MSVC (the compiler that comes with Visual Studio).If you have to do that on Windows, you could try compiling with MinGW as an alternative, or if you have to use Visual Studio, your only option is to use
malloc
to dynamically allocate the necessary memory. If you can’t do that, hope your teacher will understand…Yes, an array with length determined at run-time can be defined after
a
is defined.int array[a];
is a variable length array (VLA).It is a standard feature first in C99 and optional in later versions.
VS Community never fully supported C99.
VS versions that support C11 and later do not implement this optional feature.
Assuming VLAs are always available.
Code should assign
a
beforeint array[a];
.I’m sure that this is late, but I just wanted to let you know I was facing the same issue, and this was the solution I came up with. I couldn’t achieve this using an actual array [] so had to make a manual work around.
I’m new to coding so forgive me if this is full of extra unnecessary fluff, but with this code, you can get the users input to determine the "array length", and it also asks the user to fill in those arrays and displays the total sum of all the values along with the average.