Jon Wheelock
Jon Wheelock

Reputation: 395

Dynamic array size allocation

I had written below code in C. I expected error message since array size cannot be allocated dynamically. But the code compiles. But the result size of myArray1 is absurd. I am not sure why it compiles. I am using codeblock and minGW.

   int a;
    printf("Enter the value for a\n");
    scanf("%d",&a);
    int myArray2[a];
    printf("value of a = %d\tSize of myArray1 = %d",(sizeof(myArray2)/sizeof(myArray2[0])));

Upvotes: 0

Views: 92

Answers (1)

Buddy
Buddy

Reputation: 11028

C99 standard supports variable sized arrays on the stack.

Here is the gcc docs on it:

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

Upvotes: 2

Related Questions