Thread: Array size set by variable

  1. #1
    Registered User
    Join Date
    Mar 2005

    Array size set by variable


    I am having issues compiling a program with cc on a fairly old unix system, I understand that I need to follow C standards strictly but I can find no way around this.
    array(int n)
    int i;
    int array[n];
    It is a simple function to setup an array to size n which is collected and passed in from the main function. The compiler is freaking at the array declaration, saying that I have declared an array of 0 and that the expression is not constant, as it compiles line by line and this is the last function I am happy with the rest of my code.
    Does anyone have any ideas how I can get around this?


  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Katy, Texas
    Turn on the C99 switch in your compiler. Else, get a new compiler. Else, malloc memory from the heap for your array instead of statically allocating it in the stack.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Variable length arrays are standard, but were introduced in the 1999 version of the C standard. Your system probably has a compiler that does not support that. As such, use pointers with malloc/realloc/calloc/free instead.
    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

  4. #4
    Registered User
    Join Date
    Mar 2005
    Thanks for the quick replies, have managed a solution using malloc.

    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  2. variable array size
    By shuo in forum C++ Programming
    Replies: 39
    Last Post: 01-29-2008, 06:39 PM
  3. array of a variable size
    By dougwilliams in forum C Programming
    Replies: 3
    Last Post: 11-17-2007, 11:55 PM
  4. How do you use variable to initialize array size?
    By yougene in forum C Programming
    Replies: 11
    Last Post: 09-04-2007, 02:50 PM
  5. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM