Array size base on user input in C

Discussion in 'Mac Programming' started by icoigo, Oct 27, 2010.

  1. icoigo macrumors newbie

    Apr 4, 2010
    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.
  2. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
    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.
  3. Sydde macrumors 68020


    Aug 17, 2009
    Because array_var is not locally or statically allocated. The width parameter is effectively ignored by the compiler in this case. Try
    char *array_var[];
    and see if your code behaves any differently.

Share This Page