Hi there,
I have a question about pointers. I have two pointers: pnArray and pnPtr. The former points to a dynamically allocated array of integers and the latter points to the former. This is my code:
Code:
#include <iostream>
void print_array(int *pnArray, int nCount)
{
using namespace std;
for(int i=0; i<nCount; ++i)
cout << *(pnArray+i) << ", ";
cout << endl;
}
int main()
{
int *pnArray = new int[5];
for(int i=0; i<5; ++i)
pnArray[i] = i+i;
print_array(pnArray, 5);
int *pnPtr;
pnPtr = pnArray;
print_array(pnPtr, 5);
delete[] pnArray;
pnArray = 0;
print_array(pnPtr, 5);
return 0;
}
After freeing the allocated memory which is being pointed to by pnArray, I try to print what is pnPtr pointing to. I was expecting a crash but to my surprise, pnPtr actually did print what pnArray was pointing to!
How is this happening? Apologies if the answer is obvious, I'm still learning C++.
Thanks!