I would like to be able (if possible) to, through a single variable, access both an array and struct members. The closest I got was the following:
typedef union {
struct {
float x;
float y;
float z;
};
float getItem[3];
} Vector3D;
However, if things are done this way, everytime I want to access a Vector3D
variable as an array, I need to do it like this:
Vector3D vec;
vec.getItem[0] = 3.5f; //same as vec.x = 3.5f;
vec.getItem[1] = 8.4f; //same as vec.y = 8.4f;
vec.getItem[2] = vec.getItem[0] + vec.getItem[1]; //same as vec.z = vec.x + vec.y
I would like to know if there is any way, with any combination of typedefs, structs, unions and pointers (or with any other tool that C provides), to use the variable as both a struct and a pointer to that struct, to be accessed as an array directly, like this:
Vector3D vec;
vec[0] = 3.5f;
vec.y = 8.4f;
vec[2] = vec.x + vec[1];
I've come across a few solutions to similar problems, such as this one, but in that question, he suggests to create another variable which is a pointer to the array, whereas I would like to access both the array and the struct with the same variable, with only one declaration (as in my example). Is there any way to do it?