I recently came across a way to iterate through structs as if they were an array (as long as the value type is the same in all members of the struct) and it works as I expect it to and want it to. However, I am having trouble understanding why it works. Without understanding why it works, I do not feel comfortable using it, so I was hoping the community could help me out. Below is some code.
StructName is a generic name for my struct of many float values, and iterate is a generic function name. Please take note of the marked line as that is where I am confused on it's operation.
void iterate(StructName *s){
//some code
float *a;
a = (float*)&*s; //<---This line
//some more code
a++; //gets next struct member
}
This works as expected, I am able to iterate through my struct as an array. If I do the following (remove the (float*) from the marked line):
void iterate(StructName *s){
//some code
float *a;
a = &*s; //<---This line
//some more code
a++; //gets next struct member
}
I get the following warning:
warning: assignment to 'float *' from incompatible pointer type 'StructName *' {aka 'struct <anonymous> *'} [-Wincompatible-pointer-types]
a = &*s;
But the code still compiles and runs as expected.
And then if I do the following (remove the asterisk from the marked line):
void iterate(StructName *s){
//some code
float *a;
a = (float*)&s; //<---This line
//some more code
a++; //gets next struct member
}
My indexing is largely offset by a seemingly random amount.