How to initialize a 2D dynamic array to zero

Hi everyone,

The question is pretty straight forward, How can I initialize a 2D dynamic array to zeros?
I can imagine that it can be done with a nested for loop, by changing every [i][j] pair to zero, is this the only way?

By the way, I used new to define the array.

Thanks.
Last edited on
Yes that is the only way if you are using new
You might like using 2D vector initialized instead:
std::vector< std::vector<int> > matrix(height, std::vector<int>(width, 0));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 2D dynamic array
#include <iostream>
using namespace std;

void setVal(int **ar, const int r, const int c) {
	for (int i = 0; i < r; i++)	{
		for (int j = 0; j < c; j++)
			ar[i][j] = i+j;
	}
return;
}


int main() {
	int row=3, column=5;
	//cout << "enter row and column number:\n";
	//cin >> row >> column;

	int **arr = new int*[row];
	for (int i = 0; i < row; ++i) {
		arr[i] = new int[column];
	}

	setVal(arr, row, column);

	for (int i = 0; i < row; i++) {
		for (int j = 0; j < column; j++) {
			cout << "arr[" << i << "][" << j << "]= " << arr[i][j] << "  ";
		}
		cout << "\n";
	}

	for(int i=0; i<row; i++)
		delete[] arr[i];

	delete[] arr;

return 0;
}
Thanks to both of you, kevinkjt2000 and anup30. I think I will go with the idea of using vectors instead.
Topic archived. No new replies allowed.