Array size base on user input

This is a discussion on Array size base on user input within the C Programming forums, part of the General Programming Boards category; If I have an array which its size is based on the user input, from some material, I need to ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    14

    Array size base on user input

    If I have an array which its size is based on the user input, from some material, I need to use malloc function to allocate 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. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    Quote Originally Posted by icoigo
    Can anyone explain why it works? I thought array definition like this, its size must be explicitly determined at compile time.
    You are using a variable length array, which is a relatively new feature of C.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >You are using a variable length array, which is a relatively new feature of C.
    Not to mention that this wasn't an uncommon extension for compilers prior to C99.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 02:55 AM
  3. Trouble with DMA Segmentation Faults
    By firestorm717 in forum C Programming
    Replies: 2
    Last Post: 05-07-2006, 09:20 PM
  4. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 03-06-2005, 02:53 PM
  5. Assign array size by user
    By Brown Drake in forum C++ Programming
    Replies: 2
    Last Post: 09-11-2001, 06:45 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21