Array size base on user input in C

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

  1. macrumors newbie

    Joined:
    Apr 4, 2010
    #1
    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. macrumors 603

    Joined:
    Aug 9, 2009
    #2
    The decade-old C99 standard has variable-length arrays:
    http://en.wikipedia.org/wiki/C99

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

    Sydde

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

Share This Page