Why are dynamic 2d arrays deleted the same way as dynamic 1d array?

Hello!

My question is why are dynamic 2d arrays deleted the same way as a dynamic 1d array?

I mean this is how they're declared
1
2
3
4
    const int rowcol=3;
    int **matrix;
    matrix=new int *[rowcol];
    for(int i=0;i<rowcol;i++)*(matrix+i)=new int [rowcol];

but we delete them as a 1d array why? i mean we do extra initialization but yet we delete the same way as 1d array.
also i tried this
 
   delete [rowcol] matrix[];

but it crashes or gives me a compilation error and sometimes it will work without a problem depending on the compiler.

thank you for your answers
Last edited on
Each new should have a corresponding delete.
Each new[] should have a corresponding delete[].

In your example above, the matching deletes would look something like this:
1
2
3
4
    for (int i=0; i<rowcol; i++)
        delete []  *(matrix+i);
        
    delete [] matrix;  

I see thank you!
By the way I know that this isn't related to my question but I want to know out of curiosity.
Why do some people delete their dynamic variables with nullptr,or set them to nullptr after deleting them? and what's the difference between the three?
Why do some people delete their dynamic variables with nullptr

Are you asking this:
1
2
3
  Foo * foo = new Foo;
//  Mess with foo
  foo = nullptr;  // This does NOT delete foo.  This is a memory leak 


or set them to nullptr after deleting them?

After a delete foo; foo still points somewhere in memory, although now it's a logical error to dereference foo. By setting foo to nullptr, you're guaranteed a program trap due to an illegal address if you attempt to dereference foo (at least on architectures where memory address 0 is not a legal address).

IMO, this is a good practice in the specific case where the pointer has a lifetime longer than what was deleted. If the pointer immediately goes out of scope after being deleted, there is really no need to set it to nullptr.

Thank you again.
Though you did open lot of questions for me.I don't think it will be a great idea to ask them since my main question has been answered.But I will ask this can you or someone explain what it means to be legal?Or direct me to a guide or something to read it.

Thank you!
Topic archived. No new replies allowed.