1

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?

2
  • 3
    Make a global pointer and allocate its memory in main() Commented Dec 23, 2020 at 10:43
  • A global array has a static size. This is required by the language, full stop. But you can have a global pointer that you later assign to a dynamic (malloc-ed) array. Commented Dec 23, 2020 at 10:46

2 Answers 2

3
#include <stdlib.h>   // for malloc

int *globalarray;

int main()
{
  ...
  globalarray = malloc(thesizeyouwant * sizeof(*globalarray));
  ...
  globalarray[0] = foo;
  ...
  free(globalarray);
}
Sign up to request clarification or add additional context in comments.

13 Comments

Alright, so I guess there is no way of having the array on the stack. Thanks. One question: What is behind the expression *globalarray? The *-operator follows the pointer right? But when the expression is evaluated the pointer was not (explicitly) assigned to any memory location.
@David it reads int* globalarray i.e. int* a pointer to int. You might interested in this tutorial tutorialspoint.com/cprogramming/c_pointers.htm
@David You are confused it seems. so I guess there is no way of having the array on the stack. Make your mind, you want it global or local?
Ah ok thanks. But if *globalarray evaluates to int*, what would the expression globalarray evaluate to?
@David there are multiple storage durations. static (global) dynamic (heap) and local (stack). google it for a better understanding
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.