Reputation: 109
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
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
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
Reputation: 1
Don't make it a global array, make it a global pointer (to a heap-allocated array), and have it initialized appropriately.
Upvotes: 3