#include <stdio.h>
int* arr = new int[10];
int main()
{
for (int i = 0; i < 5; i ) {
arr[i] = i;
printf("%d", arr[i]);
}
return 0;
}
01234
I thought global variable cannot be allocated dynamically, because global(and static) variable is initialized before running program and the dynamic allocation occurs in running time. But the code works well!! I cannot understand why the code works..
CodePudding user response:
C allows this, while C does not.
Since you are using new
to allocate memory, you likely have accidentally used a c compiler, rather than a c compiler.
CodePudding user response:
Assuming you’re actually referencing C , the standard says that static and global variables must live for the entire program execution. This does not mean they have to be initialized at compile time although that is one way to do it unless you dynamically allocate them.
In general this is bad practice however because what happens when you try to delete/free the memory before the program ends?