MRM
MRM

Reputation: 571

struct member initialization

I have a defined struct like this one:

typedef struct tag_GLOBAL_VAR
{
    int array1[4];
    int array2[5];
    .......
    int array20[40];
 }GLOBAL_VAR;

This structure is used to define a variable in some class:

GLOBAL_VAR g_GlobalVar;

and then used in another class like this:

extern GLOBAL_VAR g_GlobalVar;

class constructor;

class destructor;

int class::Start()
{
     //g_GlobalVar.array1 = {1,2,3,4};
     //g_GlobalVar.array4 = {1,2,3};
     some code;
 }

My problem is that i can't initialize (commented lines) those 2 arrays like that, i get a error C2059: syntax error : '{' from VS. Why is this wrong and which is the solution to do it?

Upvotes: 0

Views: 430

Answers (5)

Andriy
Andriy

Reputation: 8604

If you need to initialize several member arrays at once, you may do following

const GLOBAL_VAR my_const = {{1,2,3,4}, {}, {}, {1,2,3}};  
g_GlobalVar = my_const;

Upvotes: 1

klm123
klm123

Reputation: 12915

This is wrong because this is not initialization, but setting a new value. Your arrays are already initialized when you declared g_GlobalVar.

I see 2 solution: A) to create new arrays, initialize them like you trying to do and copy new array in you arrays in loops; B) to set each entry of each array separately.

Upvotes: 5

eq-
eq-

Reputation: 10096

The special array initializer syntax is only available at, you guessed it, array initialization. At other times, you have to set the values one by one.

However, struct assignment (combined with initializers) allows for a shortcut, like this:

GLOBAL_VAR temporary = { {1,2,3}, {4,5,6} };
g_GlobalVar = temporary;

Other solutions include using memcpy:

int temp1[] = {1,2,3,4};
memcpy(g_GlobalVar.array1, temp1, sizeof temp1);

Upvotes: 2

Etherealone
Etherealone

Reputation: 3558

The in-place init ({...}) is only supported in C++11 for PODs.

Upvotes: 0

Lyubomir Vasilev
Lyubomir Vasilev

Reputation: 3030

You cannot initialize the values of an array in such way after its declaration. Such syntax is only possible when you declare and set an array at once, like this:

int array[5] = {1, 2, 3, 4, 5};

In all other places, you will have to set every element.

Upvotes: 1

Related Questions