C ++ array initialization
This is normal:
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};
which gives
error: cannot convert '<brace-closed initialization list> to' int in assignment
I have read many posts about this error, but it is still not clear where the problem is.
First initialization. The second is an assignment attempt, but the arrays cannot be assigned.
You can do something like:
arrays vec_2 = {{1,2,3}, {3,4,5}, {4,5,6}};
If you only want to initialize vec_2.x, you can just leave the rest of the initializers:
arrays vec_2 = {1,2,3};
In this case, the rest vec_2
will be zero-initialized.
As long as you must include at least one set of curly braces around the initializers, you don't need to include "inner" ones if you don't want to. Enabling them may give you a little extra flexibility. For example, if you want to initialize the first two elements in vec_2.x and the first one in vec_2.y, you can use:
arrays vec_2 = {{1,2}, {3}};
In this case, you get vec_2
as if you were using it {1, 2, 0, 3, 0, 0, 0, 0, 0};
as an initializer.
This is an assignment, not an initialization:
arrays vec_2;
vec_2.x = {1,2,3};
Use the following, which is equivalent to what you tried:
arrays vec_2 = { {1, 2, 3 } };
If you also want to specify values for y
and z
:
arrays vec_2 = { {1,2,3}, // x
{4,5,6}, // y
{7,8,9} // z
};
arrays vec_2;
vec_2.x = {1,2,3};
As the error message says, the second line is an assignment, not an initialization. These are 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
};
Please note that it is ,
allowed after the last internal binding! (i.e. {7,8,9},
- allowed). Trailing commas like this are usually useful for generated code: you can add another line without worrying about the comma, and you don't need to consider any special case for the last line.
int vec_1[3] = {1,2,3};
Even though it looks like it is not an assignment, it is (effectively) a constructor call. It creates an array int
initialized with these values.
arrays vec_2;
This creates a structure and each of the member arrays with default values.
vec_2.x = {1,2,3};
You cannot assign arrays and this element has already been created. The workaround is as follows:
arrays vec_2 = { {1, 2, 3} };
which is the same as
arrays vec_2 = { {1, 2, 3}, {0, 0, 0}, {0, 0, 0} };
In the first example, you are initializing the vector when you declare it.
In the second example, you are doing initialization twice (illegally), once when you declare arrays struct
and then again when you sayvec_2.x = {1,2,3}