jlanza
jlanza

Reputation: 1258

Array and struct initialize in C++

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?

Upvotes: 4

Views: 2216

Answers (2)

vrbilgi
vrbilgi

Reputation: 5793

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';

Upvotes: 0

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

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

Upvotes: 1

Related Questions