C++: Multidimensional Array Initialization in Constructor

I want to use a two dimensional array of constant size as a class member in C++. I have problems initializing it in the constructor though.

Here are my non-working tries:

1.)

class A {
 public:
  int a[2][2];
  A();
};

A::A() {
a = {{1,2},{2,4}};
}

yields: error: assigning to an array from an initializer list

2.)

class A {
 public:
  int a[2][2];
  A();
};

A::A() {
int b[2][2] = {{1,2},{2,4}};
a = b;
}

yields: invalid array assignment

3.)

class A {
 public:
  int **a;
  A();
};

A::A() {
int b[2][2] = {{1,2},{2,4}};
a = b;
}

yields: cannot convert ‘int [2][2]’ to ‘int**’ in assignment

I come from C background. I know that I could use std::vector and I am aware of the disadvantages this approach has but since this is an exercise for me I would like to know how to get it working with plain arrays. I should add that I want to work on this array later on. I want to change the stored values but not the size. Maybe that matters as well (I figured a const at the right place could help somehow?).

5 Answers

If you have C++11, you can use this syntax in the constructor definition:

A() : a{{1,2}, {3, 4}} {}

If you don't have C++11, you will need to stick to the wicked old ways:

A() {
  a[0][0] = 1;
  // etc
}

The first example also uses the constructor init-list, which should always be used to initialize members instead of intializing them in the constructor body.

13

various multidimensional array in constructor by example:

// int array1[1];
A() : array1{0} {}

// int array2[2][2];
A() : array2{{0}} {}

// int array3[3][3][3];
A() : array3{{{0}}} {}

Try this, it works for bidimensional array (in standard C++):

 class A {
 public:
  int a[2][2];
  A();
};


typedef struct{ int a[4]; } array_t;

A::A() {

 int at[2][2] = {{1,2},{2,4}};

*(array_t*)a = *(array_t*)at;

}

Ciao Angelo

4

Your first variant is extremely close to the right C++11 syntax:

A::A()
    : a{{1,2},{2,4}}
{
}
2

To complement the previous answers (you guys are so fast):

What you were trying to do in case 1 and 2 is array assignment, not permitted, as compiler says ;

But I would like to draw your attention to your third case, that's a grave misconception, specially coming from C as you say.

Assigning to a a pointer to a local variable?

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest