10

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?

7
  • 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...}. Commented Jun 29, 2015 at 11:37
  • 1
    @CoryKramer Really? I think all elements will be 0 after ={0} since the value initialized int is 0. Commented Jun 29, 2015 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. Commented Jun 29, 2015 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? Commented Jun 29, 2015 at 11:39
  • 3
    @NafeeurRahman Don't encourage the use of memset in C++, prefer at least std::fill Commented Jun 29, 2015 at 11:42

7 Answers 7

23

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.

Sign up to request clarification or add additional context in comments.

13 Comments

@EdwardBlack you must have used a non-constant size for the array. Use it like const int N = 10; int myarray[N][N] = {0};
@EdwardBlack if you are using a dynamically sized array (size is defined with variables) you will have to use memset.
@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.
@mziccard How was that rude? I did not insult anyone, I just stated how very bad I think using memset here would be.
@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 :)
|
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.

5 Comments

I tried "myarray[10][20] = {}; Does not work, i get "[Error] variable-sized object 'myarray' may not be initialized"
@EdwardBlack Cannot reproduce. MCVE or it didn't happen.
@EdwardBlack; try int myarray[10][20] = {}; instead.
@Cheersandhth.-Alf sry, actually i tried it like this, i just simplified it in the comments: pasteall.org/59235/c. I figured out that it does only work if you are using constants
@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 (coliru.stacked-crooked.com/a/557be25a7ab19089).
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

1 Comment

Thx for this alternative, but is it possible to create 3D Arrays too with vectors?
2

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.

Comments

1

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

Comments

0

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.