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: 
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);
}

```
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
}

```