Question 1:
Here's a good SO post about
stack and
heap, which will help me answer your first question:
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap
I assume that since you're confused, you probably don't know what stack and heap are, and that's fine. You probably know already that when your program runs, it is given a certain amount of memory space by the program, which is divided up into areas to store static variables, the stack, and the heap.
The stack has a limited size, and is used to store temporary variables allocated for the duration of a function call. when you declare an array in any function, it is allocated on the stack. So if your array is too large, you'll exhaust all the space there and your program will crash because it has no more room to store any variables for your function.
The heap is much larger than the stack, and it is where all dynamically memory allocations happen. So in the stack overflow article you referenced, it was suggested to dynamically allocate the array on the heap, because those variables don't take up precious room on the stack.
One final area of memory is reserved for global variables, since they are outside the scope of everything. In C++, static variables live here as well.
Question 2:
Here's a good reference on
variable scoping. This should answer part of your question:
http://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm
The short answer is
no. It's important to remember that main() is still like any other function. The only difference is that it is called first. Any variables declared inside a function
and not dynamically allocated are deallocated when execution gets to the end of the function.
Question 3:
All variables in your program only exist in the scope of your program. When your program is finished, the globals are also deallocated.
Question 4:
static
is a keyword, so it can be used on variables regardless of whether they are global. See
http://www.cprogramming.com/tutorial/statickeyword.html. Some global variables can be static, but not all static variables are global!