Thread: Array size base on user input

  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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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,897
    >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, 03: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, 03: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