skip to Main Content

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


  1. 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…

    Login or Signup to reply.
  2. Can arrays provide and after defined length in C? And Why it doesn’t work on VS Community

    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.


    What is the problem?

    • Assuming VLAs are always available.

    • Code should assign a before int array[a];.

    Login or Signup to reply.
  3. 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.

    #include<stdio.h>
    
    int main(void)
    {
    //set variables
    int a, b, i, sum = 0, avg;
    
    
    //how many scores to average?
    printf("How many scores do you want to average?: ");
     scanf("%d", &a);
    
    
    //collect scores
    for (i = 0; i < a; i++)
    {
    printf("Enter scores: ");
    scanf("%d", &b);
    sum = sum + b;
    }
    // print sum
       printf("The Sum of your array = %d n", sum);
    //results
        avg = sum / a;
        printf("The Average of your array = %d", avg);
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search