1

I'm actually working on an assignement in C, and for the need of my implementation, I need to use a static array, let's say

static int array[LEN];

The trick is that this array length, LEN, is computed in the main(). For example

static int LEN;

void initLen(int len) {
LEN = len;
}

static int array[LEN];

Where initLen is called in the main, and len is computed using the arguments given by the user.

The issue with this design, is that I get the error

threadpool.c:84: error: variably modified ‘isdone’ at file scope

The error is due to the fact that we cannot initialize static arrays using variables as length. To make it work, I'm defining a LEN_MAX and write

#define LEN_MAX 2400

static int array[LEN_MAX]

The issue with this design is that i'm exposing myself for buffers overflows and segfaults :(

So I'm wondering if there is some elegant way to initialize a static array with the exact length LEN?

Thank you in advance!

2
  • What is isdone and what does it have to do with your array? Nowhere in your question, except the error message, is this isdone variable mentioned. Please provide a SSCCE instead. Commented Apr 8, 2013 at 15:13
  • @JoachimPileborg well isdone is just the real array in my program, array that I simply called array in my example. Commented Apr 8, 2013 at 15:55

2 Answers 2

6
static int LEN;
static int* array = NULL;

int main( int argc, char** argv )
{
    LEN = someComputedValue;
    array = malloc( sizeof( int ) * LEN );
    memset( array, 0, sizeof( int ) * LEN );
    // You can do the above two lines of code in one shot with calloc()
    // array = calloc(LEN, sizeof(int));
    if (array == NULL)
    {
       printf("Memory error!\n");
       return -1;
    }
    ....
    // When you're done, free() the memory to avoid memory leaks
    free(array);
    array = NULL;
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest to use malloc:

static int *array;

void initArray(int len) {
   if ((array = malloc(sizeof(int)*len)) != NULL) {
      printf("Allocated %d bytes of memory\n", sizeof(int)*len);
   } else {
      printf("Memory error! Could not allocate the %d bytes requested!\n", sizeof(int)*len);
   }
}

Now don't forget to init the array before you can use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.