It is known that the new operator in C++ allocates block of memory. But it seems that using the new operator to allocate an array of items allows us to use many more items than static declaration does. For example if I declare a static array of integer elements like this, the compiler may report a stack overflow error:
int A[1000000]; //the program shows a stack overflow error here
But when I replace it by a pointer, the program runs properly:
int *A = new int[1000000]; //it works
I do not understand how it works. Please explain me why. Thank you very much!
There are different regions of memory. One of these regions is called the "stack". It is a small amount of memory given by the operating system to your program when it starts. Variables created without new or malloc are put on the stack.
int A[1000000];
Too much for the stack.
There is another region of memory known as the heap. This is a much bigger region. You get to use the heap when you create a variable with new or malloc.
int *A = newint[1000000]; Goes on the heap. The heap is big.
Now that you know the technical terms "stack" and "heap" you can look them up.