I was reading this article ( http://www.codeproject.com/Articles/627/A-Beginner-s-Guide-to-Pointers ) which has some code to explain one reason why we should use them. eg. Dynamic Allocation.
Eg.1. The incorrect program:
"This program firstly calls the SomeFunction function, which creates a variable called nNumber and then makes the pPointer point to it. Then, however, is where the problem is. When the function leaves, nNumber is deleted because it is a local variable. Local variables are always deleted when execution leaves the block they were defined in. This means that when SomeFunction returns to main(), the variable is deleted. So pPointer is pointing at where the variable used to be, which no longer belongs to this program."
#include <stdio.h>
int *pPointer;
void SomeFunction()
{
int nNumber;
nNumber = 25;
// make pPointer point to nNumber:
pPointer = &nNumber;
}
void main()
{
SomeFunction(); // make pPointer point to something
// why does this fail?
printf("Value of *pPointer: %d\n", *pPointer);
}
Eg.2. The Correct program:
"When SomeFunction is called, it allocates some memory and makes pPointer point to it. This time, when the function returns, the new memory is left intact, so pPointer still points to something useful. That's it for dynamic allocation!"
#include <stdio.h>
int *pPointer;
void SomeFunction()
{
// make pPointer point to a new integer
pPointer = new int;
*pPointer = 25;
}
void main()
{
SomeFunction(); // make pPointer point to something
printf("Value of *pPointer: %d\n", *pPointer);
}
My Question:
This above explaination made complete sense to me and I was feeling good about why we use pointers. Then I decided to run the programs to see what happens. I was expecting the first one to display some random number for *pPointer because the 25 had been deleted. Both programs displayed "Value of *pPointer: 25" correctly. Shouldn't the first program have failed as the tutorial said it would?