Delete a row in a dynamically allocated multi-dimension array

in this piece of code i have a matrix and if a sum of a row is not even, i have to delete it, but how to delete a row in a dynamically allocated multi-dim array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  void filterMat(int**& matrix, int cols, int& rows)
{
	int sumRows = 0;
	for (size_t i = 0; i < rows; i++)
	{
		sumRows = 0;
		for (size_t j = 0; j < cols; j++)
		{
			sumRows += matrix[i][j];
		}

		if (sumRows % 2 != 0)
		{
			delete[]matrix[i];
			matrix[i] = nullptr;
		}
	}
}


this throws an exception so its no corect but i cound think of any other way to delete it

also should do this task without extra memory /without creating a new dyn alloc multi-dimensional array/
Last edited on
I don't see anything wrong in the code that you posted.

Does the code that use the "matrix" after this function is finished handle rows that are null properly (this function does not)?
After this func I just try to use my printMatrix func and it throws exeption

1
2
3
4
5
6
7
8
9
10
11
12
void printMatrix(int** matrix, int rows, int cols)
{
	for (size_t i = 0; i < rows; i++)
	{
		for (size_t j = 0; j < cols; j++)
		{
			cout << matrix[i][j] << ' ';
		}
		cout << endl;
	}
}


this printMatrix func i am 100% that its correct
That function does not check if a row is null before trying to print it.
Last edited on
Hello izlezotfilma,

Until I have a chance to set something up, which may not match the code that you have, I am thinking that in the "filterMat" function first you would have to delete all the columns before you delete the row. and instead of matrix[i] = nullptr;, because there would be no "matrix[i]" you would need rows--;.

You could also write if (sumRows % 2). As long as the returned value is something other than (0) it would be true.

Posting enough code to duplicate your problem if very helpful.

Andy
You need to move the rows above the deleted row back one and subtract 1 from rows.
Something like:

1
2
3
4
5
6
7
		if (sumRows % 2 != 0)
		{
			delete[] matrix[i];
			for (int k = i + 1; k < rows; ++k)
			    matrix[k - 1] = matrix[k];
			matrix[--rows] = nullptr;
		}

I was thinking something similar Dutch. If they're going to be moved anyways just overwrite the row being deleted and delete the end or just disregard it via a separate tally.
Thank you very much everyone!
Topic archived. No new replies allowed.