Jeremy Guy
Jeremy Guy

Reputation: 109

Global array declaration in C?

I need to declare an array globally, because I want all methods to be able to access it in the main.c program. However, if I declare it in main.h, I will have to give it a size at declaration time - the problem is, I don't know the size until InitializeMemory(...) method is called, which takes user input to be the size of the array.

Upvotes: 0

Views: 3374

Answers (3)

kbyrd
kbyrd

Reputation: 3351

If you need to allocate a global array at with the size only known at runtime, then you want to just a pointer and then you'll malloc in your code once you know the size.

 int *array;
 ...
 array = malloc(size_from_initialize_memory_function);
 // check that array != NULL.

Upvotes: 2

Fatih Donmez
Fatih Donmez

Reputation: 4347

Create it like int *ptr; globally (let say it's integer); then in your function;

 ptr = (int *) malloc(100*sizeof(int));

Upvotes: 3

Don't make it a global array, make it a global pointer (to a heap-allocated array), and have it initialized appropriately.

Upvotes: 3

Related Questions