jeudi 21 mai 2015

Why does this work? Assigning a new int value to a pointer after delete

I have this code:

#include <iostream>

using namespace std;

void main(){
    int *ptr = new int(15);

    cout << "Address of ptr: " << ptr << endl;
    cout << "Content of ptr: " << *ptr << endl << endl;

    delete ptr;
    *ptr = 30;

    cout << "Address of ptr: " << ptr << endl;
    cout << "Content of ptr: " << *ptr << endl;
}

And this is the output:

Address of ptr: 007B81F0
Content of ptr: 15

Address of ptr: 007B81F0
Content of ptr: 30

Why does this work? Why can I still use the pointer? What happened?

Is this useful at some point?

Aucun commentaire:

Enregistrer un commentaire