0

I have a whole program that is working with pointers, dynamically allocating and arrays, etc.

My last function that was given to me is a function to delete matrix. Here is the given information:

/*
  Deletes a two dimensional dynamically allocated matrix
  -- rows: The number of rows in the matrix
  -- **matrix: the matrix to be deleted
*/
void delete_matrix(int rows, char **matrix)
{
  delete[] matrix;
}

My question is, is this right? and also why is a value for rows being passed in?

Spencer Apel
  • 31
  • 2
  • 11
  • 6
    How was it allocated? – Alex Huszagh Jan 31 '18 at 03:48
  • 2
    Possible duplicate of [How to delete this 2d dynamic array in c++](https://stackoverflow.com/questions/28711893/how-to-delete-this-2d-dynamic-array-in-c) – xskxzr Jan 31 '18 at 03:48
  • 1
    Don't use new and delete. Use an STL container that does de-allocation when the container's destructor is invoked, or else use some smart pointer. In modern C++, new and delete are mainly for writing custom allocators or other low level library code. – Jive Dadson Jan 31 '18 at 06:24

1 Answers1

0

With dynamically allocated arrays, you can think of them as arrays of arrays. What is happening behind the scenes is that there is a pointer to an array of pointers, and you have to free the memory for each of the pointers down the line, not just the main one. Long story short, you need the number of rows because you need to delete each row in the array to avoid a memory leak before you delete the main array.
It should look something like this:

/*
  Deletes a two dimensional dynamically allocated matrix
  -- rows: The number of rows in the matrix
  -- **matrix: the matrix to be deleted
*/
void delete_matrix(int rows, char **matrix)
{
  for(int i = 0; i < rows; ++i)
  {
     delete matrix[i];
  }

  delete[] matrix;
}

Edit: The above is assuming that you used new to create the array. If you used malloc instead, you would need to put free(matrix) instead of delete[] matrixand put free inside the for() loop as well instead of delete.

Hawkeye5450
  • 672
  • 6
  • 18