Jon Wheelock Jon Wheelock - 1 year ago 94
C Question

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");
int myArray2[a];
printf("value of a = %d\tSize of myArray1 = %d",(sizeof(myArray2)/sizeof(myArray2[0])));

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download