Ok, I have an extremely simple program. This compiles and (as far as I know) it works fine.
simple enough. However I never called delete on the pointer, aren't you supposed to always do that? However in this code, when I call delete on pVariable, I get a runtime errorCode:#include <iostream> #include <conio.h> using namespace std; int main() { int localvariable = 5; int age = 16; int * pVariable = &localvariable; cout << "Localvariable is " << localvariable << endl; cout << "*pVariable points to localvariable " << endl; cout << "*pVariable is " << *pVariable << endl; cout << "Now I want to change what *pVariable points to " << endl; pVariable = &age; cout << "Age is " << age << endl; cout << "*pVariable = &age" << endl; cout << "*pVariable is " << *pVariable << endl; getch(); return 0; }
Why does the top code work, but the bottom code doesn't?Code:#include <iostream> #include <conio.h> using namespace std; int main() { int localvariable = 5; int age = 16; int * pVariable = &localvariable; cout << "Localvariable is " << localvariable << endl; cout << "*pVariable points to localvariable " << endl; cout << "*pVariable is " << *pVariable << endl; cout << "Now I want to change what *pVariable points to " << endl; pVariable = &age; cout << "Age is " << age << endl; cout << "*pVariable = &age" << endl; cout << "*pVariable is " << *pVariable << endl; delete pVariable; //<--THIS IS THE ONLY CHANGE getch(); return 0; }



LinkBack URL
About LinkBacks


