4

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?

3
  • 4
    This is C99, not C in general... Commented Oct 22, 2010 at 11:07
  • @Oli: Though that was 11 years ago. Would be nice to not have to specify... :/ Commented Oct 22, 2010 at 11:25
  • 1
    @GMan: It may be 11 years ago, but there are still plenty of platforms that don't really support C99 (embedded springs to mind). If someone says "C" to me, I assume they mean the common denominator of all dialects. YMMV... Commented Oct 22, 2010 at 11:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.