Why “delete [][]… multiDimensionalArray;” operator in C++ does not exist

后端 未结 9 980
清酒与你
清酒与你 2021-02-05 06:09

I was always wondering if there is operator for deleting multi dimensional arrays in the standard C++ language.

If we have created a pointer to a single dimensional arra

相关标签:
9条回答
  • 2021-02-05 06:46

    You can use a wrapper class to do all those things for you. Working with "primitive" data types usually is not a good solution (the arrays should be encapsulated in a class). For example std::vector is a very good example that does this.

    Delete should be called exactly how many times new is called. Because you cannot call "a = new X[a][b]" you cannot also call "delete [][]a".

    Technically it's a good design decision preventing the appearance of weird initialization of an entire n-dimensional matrix.

    0 讨论(0)
  • 2021-02-05 06:49

    not sure of the exact reason from a language design perspective, I' guessing it has something to do with that fact that when allocating memory you are creating an array of arrays and each one needs to be deleted.

    int ** mArr = new int*[10];
    for(int i=0;i<10;i++)
    {
       mArr[i]=new int[10];
    }
    

    my c++ is rusty, I'm not sure if thats syntactically correct, but I think its close.

    0 讨论(0)
  • 2021-02-05 06:55

    Technically, there aren't two dimensional arrays in C++. What you're using as a two dimensional array is a one dimensional array with each element being a one dimensional array. Since it doesn't technically exist, C++ can't delete it.

    0 讨论(0)
提交回复
热议问题