Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct array initialization

This is ok:

int vec_1[3] = {1,2,3};

so what's wrong with

struct arrays{
  int x[3];
  int y[3];
  int z[3];
};
arrays vec_2;
vec_2.x = {1,2,3};

that gives:

error: cannot convert ‘<brace-enclosed initializer list>’ to ‘int’ in assignment

I've read a lot of posts on this error but it's still not clear where the problem is.

like image 766
brunetto Avatar asked Oct 19 '25 09:10

brunetto


1 Answers

The first is initialization. The second is an attempt at assignment, but arrays aren't assignable.

You could do something like:

arrays vec_2 = {{1,2,3}, {3,4,5}, {4,5,6}};

If you only want to initialize vec_2.x, then you can just leave out the rest of the initializers:

 arrays vec_2 = {1,2,3};

In this case, the rest of vec_2 will be initialized to contain zeros.

While you have to include at least one set of braces around the initializers, you don't have to include the "inner" ones if you don't want to. Including them can give you a little extra flexibility though. For example, if you wanted to initialize the first two items in vec_2.x and the first one in vec_2.y, you could use:

arrays vec_2 = {{1,2}, {3}};

In this case, you'll get vec_2 set as if you'd used {1, 2, 0, 3, 0, 0, 0, 0, 0}; as the initializer.

like image 81
Jerry Coffin Avatar answered Oct 21 '25 21:10

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!