Azhar Ali
Azhar Ali

Reputation: 59

Proper way to Initialize C++ struct that has other structs and array

I have the following code and I need to initialize the XYZ struct. Please give me a way to do this.

struct Demo
{
    int abc[10];
    int reply_port;
};

struct XYZ 
{
    struct Demo dem[10];
    int x;
    int y;
    struct Demo a;
    struct Demo b;
    struct Demo c;
} arr[100];

Demo1 is another struct that is available in other file. Please tell me an efficient way in how this struct XYZ can be initialized.

Thanks

Upvotes: 0

Views: 197

Answers (3)

Dmitry Ledentsov
Dmitry Ledentsov

Reputation: 3660

Init to all 0's

XYZ xyz = {};

No init: http://ideone.com/wE7MCF → undefined behavior

Init: http://ideone.com/BT81PH → all 0s

Upvotes: 1

Michael Kruglos
Michael Kruglos

Reputation: 1286

I don't know why do you want to do it this way, but if you insist:

  struct XYZ myXYZ = { 
    {   
      // dem[10]
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80}
    },  
    10, // x
    20, // y
    {{1,2,3,4,5,6,7,8,9,10},80}, // a
    {{1,2,3,4,5,6,7,8,9,10},80}, // b
    {{1,2,3,4,5,6,7,8,9,10},80}  // c
  };

I would think of designing it differently, but I don't know what problem you're trying to solve.

Upvotes: 2

Sanskar Katiyar
Sanskar Katiyar

Reputation: 7

Why won't you use class? Further in the class you may define a parameterized constructor.

Or do you want to do it with structures only?

Upvotes: 0

Related Questions