View Full Version : Array size base on user input in C

Oct 27, 2010, 12:37 PM
If I have an array which its size is based on the user input, from some material, I need to use malloc function to allocation memory for that array what is known dynamic array. Don't forget to free it.
That's fine, however, I like to try things out even I know the program will crash.
I have written some test program on my Mac using C language like this:

int width = 0;
//get user input, and assign the input value to width, for example, 3

char * array_var[width];

and width is an int, its value will be assigned by the user input. The point is, this program work as expected, for example, in command line, I input 3, then array_var length is 3, its size is 3 * sizeof(char *).

Can anyone explain why it works? I thought array definition like this, its size must be explicitly determined at compile time. I am lost.

Oct 27, 2010, 12:48 PM
The decade-old C99 standard has variable-length arrays:

There is a big difference, however, between a locally declared array and a malloc'ed one.

Oct 27, 2010, 02:23 PM
Because array_var is not locally or statically allocated. The width parameter is effectively ignored by the compiler in this case. Trychar *array_var[]; and see if your code behaves any differently.