Kalmar
Kalmar

Reputation: 195

Initialize a 2D array with zero in the constructor C++

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

Answers (5)

BernieP
BernieP

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

Artur
Artur

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:

ZeroMemory on msdn

Upvotes: 1

A.B.
A.B.

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

Matt
Matt

Reputation: 6050

use memset. For example:

int a[10][10]; 
memset(a, 0, sizeof(int)*10*10);

Upvotes: 3

Octopus
Octopus

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

Related Questions