9

In C++ you can initialize a one dimensional array with 0 with a code like this:

int myarray[100] = {0};

Is there a similar way for multidimensional arrays? Or am i forced to initialize it manually with for loops?

Black
  • 18,150
  • 39
  • 158
  • 271
  • Just so you know `int myarray[100] = {0};` only initializes the **first element** to `0`, if you said for example `={5}`, the array would contain `{5, 0, 0, 0...}`. – Cory Kramer Jun 29 '15 at 11:37
  • 1
    @CoryKramer Really? I think all elements will be 0 after `={0}` since the value initialized `int` is 0. – Baum mit Augen Jun 29 '15 at 11:38
  • @CoryKramer I'm pretty sure that's false when you're actually using `{0}`. With other values, yes, you're correct, but `{0}` is special in this case. – Sam Estep Jun 29 '15 at 11:39
  • 1
    Yes they will all be zero, I was just letting the OP know that them getting all zeros is a coincidence, if they use that type of initialization to populate the array with all a particular number, that is not a way to do it. Notice in my example all the trailing values were 0's? – Cory Kramer Jun 29 '15 at 11:39
  • @CoryKramer OK. Your first comment, however, is incorrect. `int myarray[100] = {0};` initializes *all* the elements of `myarray` to 0. – Sam Estep Jun 29 '15 at 11:40
  • @CoryKramer I get what you try to say. You should however state that more precisely to avoid confusion IMO. – Baum mit Augen Jun 29 '15 at 11:42
  • 3
    @NafeeurRahman Don't encourage the use of `memset` in C++, prefer at least `std::fill` – Cory Kramer Jun 29 '15 at 11:42

7 Answers7

22

You do it exactly the same way

int marr[10][10] = {0};

Edit:

This is a C solution. For a C++ solution you can go for:

int marr[10][10] = {};

These 2 solutions do not work for arrays that have size defined via variables. e.g.:

int i, j = 10;
int marr[i][j];

To initialize such an array in C++ use std::fill.

mziccard
  • 2,158
  • 9
  • 17
  • the compiler says `warning: missing braces around initializer for ‘int [10]’ [-Wmissing-braces]`. – mch Jun 29 '15 at 11:42
  • Does not work. I get "[Error] variable-sized object 'myarray' may not be initialized" – Black Jun 29 '15 at 11:55
  • @mch To remove the warning, surround with braces like `int marr[10][10] = {{0}};` – Shreevardhan Jun 29 '15 at 11:55
  • 2
    @EdwardBlack you must have used a non-constant size for the array. Use it like `const int N = 10; int myarray[N][N] = {0};` – Shreevardhan Jun 29 '15 at 11:58
  • In C `{0}` is the universal zero initializer equivalent to C++'s `{}`. I think that here GCC erroneously outputs a warning. – mziccard Jun 29 '15 at 12:00
  • 1
    @EdwardBlack if you are using a dynamically sized array (size is defined with variables) you will have to use `memset`. – mziccard Jun 29 '15 at 12:01
  • 5
    @mziccard NO! Stop advertising `memset` for this task! While it would work in this particular case, there are too many pitfalls. This is C++, not C. Use `std::fill`. – Baum mit Augen Jun 29 '15 at 12:02
  • @BaummitAugen My bad, I was writing with C in mind (even my answer is C code). But please, try to be less rude. – mziccard Jun 29 '15 at 12:09
  • 1
    @mziccard How was that rude? I did not insult anyone, I just stated how very bad I think using `memset` here would be. – Baum mit Augen Jun 29 '15 at 12:13
  • 1
    @BaummitAugen writing in capital letters is never nice (NO) nor is using '!'. The first version of your comment contained no explanation. Anyway, I upvoted your comment and you are totally right :) – mziccard Jun 29 '15 at 12:17
  • @mziccard i also upvoted your solution, because it is working, but you could add a note to explain that it does only work with constant values. – Black Jun 29 '15 at 12:19
  • 1
    @EdwardBlack Arrays themselves only work with constant expressions in C++. Variable length arrays are a compiler extension by gcc and clang. – Baum mit Augen Jun 29 '15 at 12:21
  • @BaummitAugen for me it always worked well with variable expressions until now, but i will use constants now. – Black Jun 29 '15 at 12:26
8

A multidimensional array is an array of arrays.

The same general array initialization syntax applies.

By the way you can just write {}, no need to put an explicit 0 in there.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • I tried "myarray[10][20] = {}; Does not work, i get "[Error] variable-sized object 'myarray' may not be initialized" – Black Jun 29 '15 at 11:57
  • @EdwardBlack [Cannot reproduce](http://coliru.stacked-crooked.com/a/75514fc7e2f0a90f). [MCVE](http://stackoverflow.com/help/mcve) or it didn't happen. – Baum mit Augen Jun 29 '15 at 11:58
  • 1
    @EdwardBlack; try `int myarray[10][20] = {};` instead. – Cheers and hth. - Alf Jun 29 '15 at 12:02
  • @Cheersandhth.-Alf sry, actually i tried it like this, i just simplified it in the comments: http://www.pasteall.org/59235/c. I figured out that it does only work if you are using constants – Black Jun 29 '15 at 12:11
  • @EdwardBlack: That's using C99 variadic arrays. It's not standard C++ code, and it will be rejected by the compiler in standards-mode. See (http://coliru.stacked-crooked.com/a/557be25a7ab19089). – Cheers and hth. - Alf Jun 29 '15 at 12:19
5

use vector instead of array it will give you more flexibility in declaration and in any other operation

vector<vector<int> > myarray(rows,vector<int>(columns, initial_value));

you can access them same as you access array,

and if u still want to use array then use std::fill

whishky
  • 396
  • 3
  • 13
1

You could use std::memset to initialize all the elements of a 2D array like this:

int arr[100][100]
memset( arr, 0, sizeof(arr) )

Even if you have defined the size via variables this can be used:

int i=100, j=100;
int arr[i][j]
memset( arr, 0, sizeof(arr) )

This way all the elements of arr will be set to 0.

yazyyyyy
  • 11
  • 2
0

Using 2 vector containers:

std::vector<std::vector<int>> output(m, std::vector<int>(n, 0));

This way one can declare a 2D vector output of size (m*n) with all elements of the vector initialized to 0.

Yun
  • 3,056
  • 6
  • 9
  • 28
0

For "proper" multi-dimensional arrays (think numpy ndarray), there are several libraries available, for example Boost Multiarray. To quote the example:

#include "boost/multi_array.hpp"
#include <cassert>

int 
main () {
  // Create a 3D array that is 3 x 4 x 2
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;
  array_type A(boost::extents[3][4][2]);

  // Assign values to the elements
  int values = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        A[i][j][k] = values++;

  // Verify values
  int verify = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        assert(A[i][j][k] == verify++);

  return 0;
}

See also: High-performance C++ multi-dimensional arrays

Jan Christoph Terasa
  • 5,781
  • 24
  • 34
-1

In C++, simply you can also do this way:-
int x = 10, y= 10; int matrix[x][y] = {}; and then the 2d-array will be initialized with all zeroes.

Ajay jangid
  • 711
  • 9
  • 9