Search code examples
arrayscmallocsize

Integer array size in C without using dynamic memory allocation


I need to declare an array of structures with size symbolnum, but because symbolnum is variable C will produce an error when i write the following code:

extern int symbolnum;

struct SymbTab stab[symbolnum];

I already tried:

extern int symbolnum;
const int size = symbolnum;
struct SymTab stab[size];

Is there a way to achieve this without using dynamic memory allocation functions like malloc() or initializing the size of array using a very big number?


Solution

  • The size of global arrays must be fixed at compile time. VLAs are only allowed inside of functions.

    If the value of symbolnum isn't known until runtime, you'll need to declare stab as a pointer type and allocate memory for it dynamically.

    Alternately, if the array doesn't take up more than a few 10s of KB, you can define the VLA in the main function and set a global pointer to it.