tags:

views:

80

answers:

2

I would like to initilize some elements of an struct and array in C++.

In C you can do:

unsigned char array[30] = {[1] = 4, [20] = 4};
struct mystruct 
{ int i;
  int j;
}
struct mystruct e = {.j = 2};

But I cannot do it in C++. Is there any way to implement this kind of designated initializers?

+1  A: 

In C++ struct has constructors (just like class), so you could always init your var in them.

Rin
It is a struct that comes from a C lib I cannot compile :( But I was thinking on that
jlanza
A: 

Its always good to Initialize ALL the element in array or structure to avoid many errors.

Below may help you.

Initialization for struct

struct myStruct

{

   int i;

   int j;

   myStruct()
   {
       j=10; //default Constructor     
   }

};

Initialization for Array:

unsigned char array[5];

array[0]='A';

array[2]='C';