Reputation: 183
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.
Upvotes: 4
Views: 12042
Reputation: 361442
arrays vec_2;
vec_2.x = {1,2,3};
As the error message says, the second line is assignment, not initialization. They're two different things.
You need to do this:
arrays vec_2 = {
{1,2,3}, //initializes x
{5,6,7}, //initializes y
{7,8,9}, //initializes z
};
Note that ,
is allowed after the last inner-brace! (i.e {7,8,9},
<-- allowed). Such trailing comma is usually helpful for generated code: you can add another line, without caring about comma, neither do you need to consider any special case for the last line.
Upvotes: 2
Reputation: 490138
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.
Upvotes: 5
Reputation: 66922
int vec_1[3] = {1,2,3};
Despite what it looks like, this is not assignment, this is (effectively) a constructor call. It constructs a array of int
initialized to those values.
arrays vec_2;
This constructs a struct, and each of the member arrays with default values.
vec_2.x = {1,2,3};
You cannot assign arrays, and this member has already been constructed. The workaround is as such:
arrays vec_2 = { {1, 2, 3} };
which is the same thing as
arrays vec_2 = { {1, 2, 3}, {0, 0, 0}, {0, 0, 0} };
Upvotes: 2
Reputation: 121971
This is assignment, not initialization:
arrays vec_2;
vec_2.x = {1,2,3};
Use the following, which is equivalent to what you were attempting:
arrays vec_2 = { {1, 2, 3 } };
If you want to provide values for y
and z
also:
arrays vec_2 = { {1,2,3}, // x
{4,5,6}, // y
{7,8,9} // z
};
Upvotes: 3
Reputation: 6480
In the first example you are intializing the vector when you declare it.
In the second example, you are intializing twice (illegal), once when you declare the arrays struct
and then again when you say vec_2.x = {1,2,3}
Upvotes: 1