0
struct abc {
    double matrix[2][2];
};

int main(){
   abc test;
   test.matrix[2][2]={0,0,0,0};
}

I construct a struct called abc, and 2*2 matrix is its memember. But how to initialize the matrix in main function? The above code always comes with error... how to fix it?

Adam Burry
  • 1,904
  • 13
  • 20
user2756494
  • 263
  • 1
  • 4
  • 7

2 Answers2

0

gcc 4.5.3: g++ -std=c++0x -Wall -Wextra struct-init.cpp

struct abc {
  double matrix[2][2];
};

int main(){
 abc test;
 test.matrix = {{0.0,0.0},{0.0,0.0}};
}

Or maybe simple is best:

struct abc {
  double matrix[2][2];
  abc() {
    matrix[0][0] = 0.0; matrix[0][1] = 0.0;
    matrix[1][0] = 0.0; matrix[1][1] = 0.0; }
};

int main(){
 abc test;
}
Adam Burry
  • 1,904
  • 13
  • 20
0

See also this and this

You can write:

struct abc 
{
    int foo;
    double matrix[2][2];
};

void f()
{
   abc test = 
       { 
        0,        // int foo; 
        {0,0,0,0} // double matrix[2][2];
       };

}

I've added foo for clarity on why the additional set of {} around the array.

Note that this kind of structure initialisation can only be used with an aggregate data type, which roughly means a C-link struct.

If you really need to construct and then assign, you may need to do something like:

struct Matrix
{
    double matrix[2][2];
};

struct abc2 
{       
    int foo;
    Matrix m;
};

void g()
{
   abc2 test;
   Matrix init =  { 5,6,7,8};
   test.m = init;
}
Community
  • 1
  • 1
Keith
  • 6,756
  • 19
  • 23