void PrintArray()
{
int a[4] = {4,3,1,5};
for(int i=0; i<4; i++)
cout<<a[i];
}
What Exactly happens to the memory allocated to the pointer variable 'a' and the 4-integer block pointed to by 'a' after this function's call is completed? Does the memory of the block and pointer variable get de-allocated or does it create some sort of memory leak?
First, we need to clear up a basic misconception here.
a
is not a separate pointer variable distinct from the 4-element array;a
is the 4-element array. The address ofa
and the address ofa[0]
are the same thing. Under most circumstances, the expressiona
is converted from type "4-element array ofint
" to "pointer toint
", and the value of the expression is the address of the first element in the array.To answer the question, since
a
was declared within a block and without thestatic
keyword, it has automatic storage duration, meaning that the memory occupied by the array is released when you leave the enclosing scope (in this case, the body of the function).