C++ struct array initialization

brunetto picture brunetto · Mar 22, 2012 · Viewed 11.4k times · Source

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.

Answer

Jerry Coffin picture Jerry Coffin · Mar 22, 2012

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.