As I've read on cpprefrence:
Delete Deallocates storage previously allocated by a matching operator new.
But here, I only get 3.4 as an output and not 2.1.
#include <iostream>
int main(){
float x, y; x = y = 0;
float * p = &x;
*p = 3.4;
std::cout << *p;
delete p; //Can I deallocate memory of a static pointer?
p = &y;
*p = 2.1;
std::cout << *p;
delete p;
return 0;
}
UPDATE: I've added operator new
here and the code doesn't give the expected results still.
int main(){
float *p = new float(3.4);
float x, y; x = y = 0;
p = &x;
*p = 3.4;
cout << *p;
delete p; //Deallocate the memory of p pointer.
p = &y; //Shouldn't this line reallocate the memory to p? or maybe &p = &y;
*p = 2.1;
cout << *p;
delete p;
return 0;
}
We were told by our teacher to find a workaround to still be able to set a value for where the pointer is pointing at after deleting the poitner
int main(){
float *p = new float(3.4);
delete p; // We want to delete the pointer but change the value of *p afterwards.
*p = 2.1;
std::cout << *p;
}