Delete a row in a dynamically allocated multi-dimension array

Dec 29, 2020 at 3:43pm
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 Dec 29, 2020 at 3:48pm
Dec 29, 2020 at 3:50pm
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)?
Dec 29, 2020 at 3:54pm
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
Dec 29, 2020 at 4:27pm
That function does not check if a row is null before trying to print it.
Last edited on Dec 29, 2020 at 4:27pm
Dec 29, 2020 at 4:41pm
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
Dec 29, 2020 at 4:41pm
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;
		}

Dec 29, 2020 at 4:58pm
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.
Dec 29, 2020 at 5:11pm
Thank you very much everyone!
Topic archived. No new replies allowed.