Reputation: 195
What is the best way to initialize a large 2D array with 0 in the constructor? I would like to do this without having to loop through my array, if possible.
Upvotes: 2
Views: 3395
Reputation: 457
This has been answered before for a 1D array, I assume something similar for 2D?
For a constructor:
class MyClass {
int a[100];
MyClass() : a() // all zeros
{
// stuff
}
};
Upvotes: 1
Reputation: 7267
Whether it is 1D, 2D, 3D, xxD array or any other structure you may just do the following:
memset(pointer_to_your_object, 0, sizeof(your_object));
but memset in general can set memory area with any value so if that is just setting to zero you may use some of the macros that are out there - they are all called like zeromem, zeromemory etc:
Upvotes: 1
Reputation: 16670
Alternatively, use a std::vector
instead of an array.
std::vector<std::vector<int>> vec2d(100, std::vector<int>(50, 0));
The resulting two-dimensional vector will contain 100 vectors, each containing 50 zeros.
Upvotes: 4
Reputation: 6050
use memset. For example:
int a[10][10];
memset(a, 0, sizeof(int)*10*10);
Upvotes: 3
Reputation: 8325
Not sure how you allocated your "2D" array. But this is basically how I would initialize any large block of data.
int data[10000];
memset(data,0,sizeof(int)*10000);
Upvotes: 1