If I want to create an array that works as global variable, in case I already know the size I can do it this way:
#include <stdio.h>
#include <stdlib.h>
int array[]={1,1,1,1};
int main()
{
printf("%d", array[0]);
}
however, this will not work with malloc. Indeed, the following code
#include <stdio.h>
#include <stdlib.h>
int* array=malloc(4*sizeof(int));
int main()
{
printf("%d", array[0]);
}
will return an error (error: initializer element is not constant). Yet there is no problem if I try to do the same inside the scope of the function.
I believe there must be something I am missing about how dynamic allocation works.
What is going on? How can define an array dynamically outside the scope of any function and the use them as a global variable?
In C language the code can be executed only in the function bodies.
The second code is invalid as you try to call
mallocoutside the function.Using global variables in C is considered as a bad practice, so try to avoid it if not 100% necessary.
If you want to have a global pointer:
Some compilers support non-standard extensions. For example, in GCC you can use the attribute to execute the code before the function
mainis calledhttps://godbolt.org/z/bz4YjzfK5