Question: 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?

Answer: 
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;

```
No. C doesn't do that. Arrays declared in global scope have fixed space allocated for them in your binary(.EXE files on Windows and ELF executables on Linux). If you want an array of dynamic size, you need to dynamically allocate it.
Example is here:

```
#include <stdlib.h>
#define ARRAY_SIZE 100
typedef char T; //your type here
T* array;

void init() {
    array = malloc(sizeof(T) * ARRAY_SIZE); //array filled with garbage values
    //array = calloc(ARRAY_SIZE, sizeof(T)); //array filled with 0x00
}
void finish() {
    free(array); // DO NOT ACCESS ARRAY AFTER THIS CALL!
}
int main() {
    init();
    array[6] = 63; //access array as normal
    finish();
    //array[41] = 23; //will most likely crash due to a segmentation fault, also called an access violation on Windoez
}

```