Thread: How do you use variable to initialize array size?

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    182

    How do you use variable to initialize array size?

    I'm trying to initialize array bucket in bucketSort using size to initialize the size of the array. But my compiler is saying

    6.31.c:19: error: storage class specified for parameter `size'
    6.31.c: In function `bucketSort':
    6.31.c:21: error: variable-sized object may not be initialized
    6.31.c:21: warning: excess elements in array initializer
    6.31.c:21: warning: (near initialization for `bucket[0]')

    How do I do this?

    Code:
    #include <stdio.h>
    
    void bucketSort(int[], int size);
    
    
    int main()
    {
    int numbers[ 8 ] = { 9 };
    
    bucketSort( numbers, 8 );
    
    return 0;
    }
    
    
    
    
    
    void bucketSort(int array[], int size)
    {
       int bucket[ 10 ][ size ] = { 0 };
       int i, j, n;
    
       for (i = 0; i <= size - 1; ++i) {
          j = 0;
          while ( bucket[ (array[ i ] % (n * 10) ) / 10 ][ j ] != array[ i ] ) {
             if ( bucket[ (array[ i ] % (n * 10) ) / 10 ][ j ] == -1)
                bucket[ (array[ i ] % (n * 10) ) / 10 ][ j ] = array[ i ];
             else
                ++j;
          }
       }
    
    }

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by yougene View Post
    I'm trying to initialize array bucket in bucketSort using size to initialize the size of the array.
    Can't be done. You need to allocate memory dynamically with malloc().

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Not sure, doesn't C99 support variable size of stack arrays? Hence wouldn't this declaration work as it is?
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by anon View Post
    Not sure, doesn't C99 support variable size of stack arrays? Hence wouldn't this declaration work as it is?
    But only for C99! Depends on how old your compiler is ;-)
    You don't even need to malloc memory, i don't think. From what I see, the number of buckets in your prog is constant throughout, why don't you add this line into your .h
    Code:
    static const int MAX_BUCKETS = 8;
    and then replace all 8s with MAX_BUCKETS (which avoids magic numbers in any case )

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  5. #5
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by anon View Post
    Not sure, doesn't C99 support variable size of stack arrays? Hence wouldn't this declaration work as it is?
    I would NOT bet money on having a C99 compiler available. Not yet, anyway.

  6. #6
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by brewbuck View Post
    I would NOT bet money on having a C99 compiler available. Not yet, anyway.
    Plus if you program with the lowest common denominator, you guarantee your code will compile correctly everywhere :P

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  7. #7
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    If you're using MingW, there are options to enable C99 support for certain features (such as VLAs and "declare anywhere" variables) (usually found in your IDE somewhere if you're using one). If you're going with ANSI conformation, then as the others said, the only way to get around this is by using dynamic allocation of memory.
    I used to do this frequently before switching to IDEs that enable variable sized arrays and IMO it is highly worth it. The headache's you save not having to worry about calls to malloc/free and leaking memory is a huge boon especially if you have little or no concerns about your code compiling anywhere and everywhere.
    I am also tempted to make the claim that it is faster and more effecient than calling malloc and free and in general, using heap allocated memory, but I can't say for certain exactly how such arrays are implemented on a low level (i.e. how they are set up on the stack)... my guess would be that it is similar to how the compiler deals with "declare anywhere" vars (variables not declared at the top of the stack), setting up a new local stack for each variable length it encounters. Something like:
    Code:
    {
      int userInput[GetNumUserInput()];
      ...
    }
    might be converted to:
    Code:
    {
      int temp = GetNumUserInput();
      {
        int userInput[temp];
        ...
      }
    }
    Which still isn't exactly ANSI compatible, but it explains how the problem of setting up stack space when the amount of space is not yet known is addressed:
    Code:
    st &#37;sp+temp, %sp
    Of course I could be waaaaaay off on this, so anyone feel free to correct me.
    Last edited by @nthony; 09-04-2007 at 12:42 PM.

  8. #8
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Quote Originally Posted by @nthony View Post
    I am also tempted to make the claim that it is faster and more effecient than calling malloc and free and in general
    While there are certainly advantages to VLAs, such as the lack of a need to clean up and, as you state, speed, they really should be used carefully. There are two glaring, related problems with VLAs. First off, if there's not enough memory, there's no way for the programmer to know. You just get undefined behavior. This is, of course, a problem with all automatic objects but the programmer at least knows at compile-time how large objects are and can be careful. With VLAs, it's a runtime issue.

    This links in with the other problem: You're (likely) going to be able to allocate more memory with malloc(). Even a modest sized automatic array can cause problems whereas the same amount of memory will probably easily be available through malloc(). And with malloc(), if it's not, you'll know.

    So if you're using VLAs, you really have to be careful not to allocate too much. How much is too much? Well, that's hard to say, and unfortunately, the result of a too-large array is undefined.

  9. #9
    Registered User
    Join Date
    May 2006
    Posts
    182
    The thing is, the exercise seems to be telling me to initialize an array using a variable. My book came with Borland 5.5 c++ compiler if that means anything in this situation(perhaps they are writing for C99? ).

    (Bucket Sort) A bucket sort begins with an single-subscripted array of positive integers to be sorted and a double-subscripted array of integers with rows subscripted from 0 to 9 and columns subscripted from 0 to n - 1 where n is the number of values in the array to be sorted. Each row of the double-subscripted array is referred to as a bucket. Write a function bucketSort that takes an integer array and the array size as arguments.

    1) Loop through the single-subscripted array and place each of its values in a row of the bucket array based on its ones digit. For example, 97 is placed in row 7, 3 is placed in row 3 and 100 is placed in row 0.

    2) Loop through the bucket array and copy the values back to the original array. The new order of the above values in the single-subscripted array is 100, 3, and 97.

    3) Repleat this process for each subsequent digit position( tens, hundreds, thousands, etc.) and stop when the leftmost digit of the largest number has be processed)
    Last edited by yougene; 09-04-2007 at 02:41 PM.

  10. #10
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by yougene View Post
    The thing is, the exercise seems to be telling me to initialize an array using a variable. My book came with Borland 5.5 c++ compiler if that means anything in this situation(perhaps they are writing for C99? ).
    To me, it looks like the requirement is that the array be passed AS A PARAMETER. This has nothing to do with how you allocate memory internally in your bucket sort function. In other words, a function that looks like:

    Code:
    void bucket_sort(int data[], int array_size);
    That's what the requirement seems to say, when I read it.

  11. #11
    Registered User
    Join Date
    May 2006
    Posts
    182
    Then I guess my question turns into what would be the smartest way to initialize my double scripted array "bucket[][]" inside bucketSort? The size of the second subscript in bucket[][] is dependent on the size of the initial array passed. I could just set bucket[][] to a really large size and then just cut off where appropriate but that doesn't seem very elegant or reliable at all.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by yougene View Post
    Then I guess my question turns into what would be the smartest way to initialize my double scripted array "bucket[][]" inside bucketSort? The size of the second subscript in bucket[][] is dependent on the size of the initial array passed. I could just set bucket[][] to a really large size and then just cut off where appropriate but that doesn't seem very elegant or reliable at all.
    The best (fastest) way to fill memory with a value is using memset().

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Adventures in labyrinth generation.
    By guesst in forum Game Programming
    Replies: 8
    Last Post: 10-12-2008, 01:30 PM
  3. Have problems with copying my array!
    By AvaGodess in forum C Programming
    Replies: 11
    Last Post: 09-25-2008, 12:56 AM
  4. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM