Help with declaring C++ structure, with a float array as one of its members
-
06-07-2019 - |
Question
I was wondering if anyone could spot what is wrong with my structure declaration and use. At the moment I have a structure and wish to store float array as one of it's members.
My code:
struct Player{
float x[12];
float y[12];
float red,green,blue;
float r_leg, l_leg;
int poly[3];
bool up,down;
};
I then tried filling the struct:
float xcords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 };
float ycords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 };
Player player = {xcords,ycords,1,1,1,2,2,true,true};
Error:
1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float'
1> There is no context in which this conversion is possible
1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float'
1> There is no context in which this conversion is possible
Solution
Arrays decay to pointer-to-first-element of the array in most contexts as is the case with xcords
and ycords
. You cannot initialize the struct like this. So, you have to initialize the members explicitly:
Player player = {
{1,1,1,1,1,1,1,1,1,1,1,1 }, // xcords
{1,1,1,1,1,1,1,1,1,1,1,1 }, // ycords
1,1,1, // red, green, blue
2,2, // right, left
{0,1,2}, // poly[3] -- missing?
true,true}; // up, down
You are also missing initializers for poly[3] if I understand correctly. Put in the appropriate values. Otherwise there will be default initialization -- is that what you want?
OTHER TIPS
Try
Player player = {{1,1,1,1,1,1,1,1,1,1,1,1 },
{1,1,1,1,1,1,1,1,1,1,1,1 },
1,1,1,
2,2,
{},
true,true};
I think you're expecting the initialization to copy the elements of each array into your structure. Try initializing the array elements in your structure individually, say with a for
loop.
There is no "constructor" for a float array that will copy the elements of another array.