Why do I get a random value here I deleted p. Also, why is compiler allowing p[][]. I get it that p is not set to null but doesnt deleting a pointer mean that part of the memory is deallocated? And If I dont assign p = nullptr; and somehow
when I declare some object(lets say int for now), the compiler assigns it to p[0][0] and now I can access that value which is not good. So what does delete actually do ?
int main(){
int **p;
int** g;
p = newint*[4];
p[0] = newint[3];
p[1] = newint[3];
p[2] = newint[3];
p[3] = newint[3];
int count = 0;
for(int i = 0; i < 4; ++i) {
p[i][0] = ++count; p[i][1] = ++count; p[i][2] = ++count;
}
int** t = &p[0];
int** x = &p[1];
int** y = &p[2];
delete p;
cout << x[0][1] <<endl;
cout << p[0][0] <<endl; //Why do I get a random value here I deleted p.
cout << *p << endl;
}
What were you expecting? Consider this: Someone has taken your house keys, and replaced them with some other random keys; should you expect those keys to provide a sensible outcome when used for your house?
Also, why is compiler allowing p[][].
Pointers, arrays, and pointer arithmetic are very closely related. Givenint** p; then initialising p means one can do pointer arithmetic or use subscripts on a 2d array.
Just because delete de-allocates memory, it doesn't mean that access to it will produce a compile error or warning, it just means that it is invalid.
if p is going to "survive" after the deletion as an accessible entity. If p vanishes (the delete is in the destructor of a class, for example, after which p no longer exists) you can use your common sense, a sackful of pointless assignments is visual clutter and a performance hit in some cases (imagine assigning null to 10 pointers or so in a destructor ... except the user had an array of 5 million objects of your class type to destroy!).
What you have is logically the same problem as this:
int *p;
p[1962] = 11; //p is uninitialized and could be pointing to ANYTHING -- this is probably going to crash and stuff. You can DO it, the compiler allows it with just a warn, but its not correct.