Search code examples
cdynamic-memory-allocationallocation

Getting input and using it to initialize array works, but according to C , it shouldn't


the code literally gets input from user and allocates is array, and it WORKS in online gdb and geeksforgeeks problem submission?? !?!?!?

int n;
int [n];

this works!,whereas wherever I've searched, the n inside array should be a constant.

here is the link to the question and the code my friend wrote.

question

code

#include <stdio.h>
int main()
{
    int t,n;
    int rear;
    int front;
    scanf("%d",&t);
    while(t--)
    {

        scanf("%d",&n);
        int a[n],s[n];
        int temp;
        for(int i=0;i<n;i++)
            a[i]=i+1;
        front=0;
        rear=n-1;
        
        //rotation
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=i;j++)
            {
                temp=a[front];
                if(front == rear)
                {
                front = -1;
                rear = -1;
                }
                else
                {
                front = (front+1) % n;
                }

                //dequeue
                if(front == -1)
                {
                front = 0;
                }
                rear = (rear + 1) % n;

                a[rear] = temp;
                //enqueue
            }
            temp=a[front];
            if(front == rear)
            {
                front = -1;
                rear = -1;
            }
            else
            {
                front = (front+1) % n;
            }
            s[temp-1]=i;
            //dequeue

        }
        for(int i=0;i<n;i++)
        printf("%d\t",s[i]);
        printf("\n");
       

    }
    return 0;
}

Solution

  • This is a VLA, it was added in C99, but C11 onwards, it's an optional feature.

    To quote the standard:

    If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)