I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it.
How can I declare it in global scope and assign its size in the main function?
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it.
How can I declare it in global scope and assign its size in the main function?
#include <stdlib.h> // for malloc
int *globalarray;
int main()
{
...
globalarray = malloc(thesizeyouwant * sizeof(*globalarray));
...
globalarray[0] = foo;
...
free(globalarray);
}
int* globalarray i.e. int* a pointer to int. You might interested in this tutorial tutorialspoint.com/cprogramming/c_pointers.htmso I guess there is no way of having the array on the stack. Make your mind, you want it global or local?*globalarray evaluates to int*, what would the expression globalarray evaluate to?After your comment I guess there is no way of having the array on the stack, I wanted to show you that the pointer and the pointed object can have any storage. If the C implementation support Variable Length Array, you can make your global pointer point to a VLA:
int *glob_array;
int main() {
...
// obtain the size of the array in sz:
size_t sz;
sz = ...
int arr[sz];
glob_arr = arr; // a global pointer to a VLA
...
}
As arr is defined in main (and not in a sub block) it will only reach its end of life when the program will end. Yet it has automatic storage, meaning that for most implementation it will reside in the stack.
Disclaimer: the actual allocation is an implementation detail, and the compiler could allocate it in a heap if it wants to.