Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill multidimensional array elements with 0's

Tags:

c++

I have a 2d and i want to set the elements to zero without looping all the elements

int a[100][200];

I can't initialize them at point of declaration.

like image 994
user54871 Avatar asked Aug 27 '10 17:08

user54871


People also ask

How do you initialize a multidimensional array to 0?

A multidimensional array in C is nothing more than an array of arrays. Any object can be initialized to “zero” using an initializer of = { 0 } . For example: double two_dim_array[100][100] = { 0 };

How do you fill a matrix with zeros in C++?

Different Methods to Initialize 2D Array To Zero in C++int array[100][50] = {0}; The above code initialize a 2D array with all entries 0. The above code snippet actually sets the first element of the array to 0 and sets the rest of the array to 0. For example, if we replace the '0' by some other digits say '1'.

How do you assign values to a multidimensional array?

For example:int[][][] arr = new int[10][20][30]; arr[0][0][0] = 1; The above example represents the element present in the first row and first column of the first array in the declared 3D array. Note: In arrays if size of array is N. Its index will be from 0 to N-1.

How do I fill a 2D array in C++?

2-D Array filling using std::fill or std::fill_n flags[0][0], &a. flags[0][0] + sizeof(a. flags) / sizeof(a. flags[0][0]), '0'); // or using `std::fill_n` // std::fill_n(&a.


2 Answers

For C++, you can use the std:fill method from the algorithm header.

int a[x][y];
std::fill(a[0], a[0] + x * y, 0);

So, in your case, you could use this:

int a[100][200];
std::fill(a[0], a[0] + 100 * 200, 0);

Of course, the 0 could be changed for any int value.

like image 72
rcanepa Avatar answered Nov 15 '22 20:11

rcanepa


Try

int a[100][200] = {{0}};

If you initialize some (but not all) of the elements, the rest will be initialized to zero. Here, you are only explicitly initializing the first element of the first sub-array and the compiler is taking care of the rest.

like image 37
bta Avatar answered Nov 15 '22 20:11

bta