Is it possible to use a double array for a structure consisting of doubles?
struct A { double x; double y; double z; }; int main (int argc , char ** argv) { double arr[3] = {1.0,2.0,3.0}; A* a = static_cast<A*>(static_cast<void*>(arr)); std::cout << a->x << " " << a->y << " " << a->z << "\n"; }
Prints 1 2 3 . But is it guaranteed to work with any compiler every time?
EDIT: According
9.2.21: Pointer to a standard layout structure object properly converted? using reinterpret_cast, points to its initial member (...) and vice versa.
if I replace my code with
struct A { double & x() { return data[0]; } double & y() { return data[1]; } double & z() { return data[2]; } private: double data[3]; }; int main (int, char **) { double arr[3] = {1.0,2.0,3.0}; A* a = reinterpret_cast<A*>(arr); std::cout << a->x() << " " << a->y() << " " << a->z() << "\n"; }
then guaranteed work. Right? I understand that many people do not find this aesthetics pleasant, but there are advantages to working with the structure and there is no need to copy the data of the input arrays. I can define the member functions in this structure to calculate scalar and vector products, distances, etc., which will make my code much clearer than if I were working with arrays.
What about
int main (int, char **) { double arr[6] = {1.0,2.0,3.0,4.0,5.0,6.0}; A* a = reinterpret_cast<A*>(arr); std::cout << a[0].x() << " " << a[0].y() << " " << a[0].z() << "\n"; std::cout << a[1].x() << " " << a[1].y() << " " << a[1].z() << "\n"; }
Is this guaranteed to work, or can the compiler deliver something AFTER the data to sizeof(A) > 3*sizeof(double) ? And is there any portable way to prevent the compiler from doing this?
c ++ arrays language-lawyer struct static-cast
vitke
source share