Delete pointer to multidimensional array in class through another pointer - how?

前端 未结 4 2107
眼角桃花
眼角桃花 2020-12-04 03:18

I have a pointer to a class, that have a pointer to a multidimensional array but I can\'t seem to delete it from memory when I need to or set it to NULL.

#de         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 04:09

    Depends on your allocation of pArray[i][j]. If it's something like pArray[i][j] = new int; then call delete Pointer_To_TestClass->pArray[0][0];. If it's something like pArray[i][j] = new int[10] then use your second option, delete[] Pointer_To_TestClass->pArray[0][0];. I'd also highly recommend immediately following the delete with setting it to NULL and proceeding it with the check for NULL.

    The third one did not compile for me delete[][] Pointer_To_TestClass->pArray[0][0]; I got the error

    Line 34: error: expected primary-expression before '[' token compilation terminated due to -Wfatal-errors.

    Also, I'd highly recommend having those deletes in the destructor. Other places may be fine as well.

    You may find the typedef of int* to be helpful for readability understanding you have a two-dimensional array of int*.

提交回复
热议问题