4
#include "stdio.h"

int main()
    {
        int n;
        printf("Enter n:\n");
        scanf("%d",&n);

        int arr[n][n];
        arr[3][3] = 4;
        printf("%d",arr[3][3]);
        getchar();
        return 0;
    }

Wasn't using int arr[n], where n is a variable, illegal in C? I am trying to understand what's happening here. Apparently the code works on my clang LLVM compiler and on IDEOne and on Codeblocks. I guess the compiler is just making things easy for me, by doing automatic memory allocation. But another astounding fact is that when I try to set n to 1, 2 or 3 it still works.

1
  • 9
    They're illegal in ANSI C. They were added to the standard in C99. Commented Dec 28, 2013 at 8:19

1 Answer 1

6

Variable length arrays are allowed by C standard since C99. Note that they are still not allowed by C++
standard.
Also important point to note is for versions before c99 and for most C++ compilers variable length arrays are supported by implementations in the form of extensions.

Sign up to request clarification or add additional context in comments.

2 Comments

@AneeshDogra Because you're invoking undefined behavior and got lucky (or unlucky depending on how you look at it).
In fact, 3 is the same case. Your example is legal with n >= 4.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.