Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare dynamically sized array in global scope

Not using C that often, I came across a possibly simple problem. I have several functions, that need access to a global array-variable g. But the actual size of this variable has to be defined in an init()-function. The size depends on some other stuff, so g has to be declared somehow with a dynamic size. I read about malloc and other functions, but I am not sure how to use them properly.

Example:

double g[dynamic]; // size is not known yet
int n;

void init()
{
   // calculate "n" for array size
   n = ...
   // declare and initialze g with a size "n"
}

void dostuff()
{
   for (int i = 0; i < n; i++)
      work(g[i]);
}

How should I solve this?

like image 584
Lemonbonbon Avatar asked Mar 14 '26 02:03

Lemonbonbon


2 Answers

You cannot use an array. You must use a pointer.

double *global_array; // size is not known yet
size_t nglobal_array; // may be helpful to have the size

void init(void)
{
   // calculate "nglobal_array" for array size
   nglobal_array = 42;
   // declare and initialze global_array with a size "nglobal_array"
   global_array = malloc(nglobal_array * sizeof *global_array);
   if (global_array == NULL) {
       fprintf(stderr, "Error allocating resources.\nProgram aborted.\n");
       exit(EXIT_FAILURE);
   }
}

void dostuff()
{
   for (int i = 0; i < nglobal_array; i++)
      work(global_array[i]);
}

Don't forget to free(global_array) when you no longer need it.

Complete usage would then be something like this

#include <stdlib.h>
// includes
// declarations & definitions as above
int main(void) {
    init();
    dostuff();
    free(global_array);
}
like image 111
pmg Avatar answered Mar 15 '26 20:03

pmg


What you want to achieve is not possible in C.

A global array must have a fixed size at compile, or at least at link time.

You can declare the array without a specified size:

extern double g[];

But it must be defined somewhere with an actual size, computed from a constant expression at the definition place, and the size cannot be determined from the above declaration, so it must be passed some other way to the functions that will use the array: either implicitly, with a special value signifying the end of the array (like '\0' for char strings) or explicitly via a separate variable as you posted. Note however that n and g are very poor name choices for global variables as they are likely to clash with local variable names and convey no meaning to the reader.

If the size is not known until run time, you should define a pointer instead of an array and also define a separate variable with the length of the array that will be allocated by the initialization function.

double *g;
size_t g_length;
like image 20
chqrlie Avatar answered Mar 15 '26 22:03

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!