TITLE: casting between structs and arrays (Source: comp.lang.c++.moderated, 8 Oct 2000) WILLIAMS: Jim Williams >If I'm not mistaken, the language guarantees the following strangeness >is safe because the two structs begin with the same fields >(reinterpret_cast is the appropriate choice here, right?). > > struct Foo { > int a,b; > }; > > struct Bar { > int a,b,c; > }; > > Bar b; > Foo *f=reinterpret_cast(&b); > f->a=10; //safe > f->b=20; //safe CLAMAGE: Stephen Clamage I don't find such a guarantee in the standard, but the code will probably work. What is guaranteed is in section 9.2p16: "If a POD-union contains two or more POD-structs that share a common initial sequence, and if the POD-union object currently contains one of these POD-structs, it is permitted to inspect the common initial part of any of them. Two POD-structs share a common initial sequence if corresponding members have layout-compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members." If Foo and Bar are members of a union, your code is safe. WILLIAMS: >I'm wondering if the following is also safe. Since all of the fields >are the same type, there should be no need for padding within the >structs. > > int *p=reinterpret_cast(&b); > p[0]=10; //safe, modifies b.a > p[1]=20; //safe, modifies b.b > p[2]=30; //safe, modifies b.c CLAMAGE: You cannot assume that no padding is needed. For example, a system with 64-bit words might make ints 32 bits and align them on 8-byte boundaries. Since Bar does not contain an array of ints, the effect of your code is undefined. WILLIAMS: >If this is not safe, would the following alternate definition of Bar >make it so, with obvious adjustments to the preceding code? > > struct Bar { > int a[3]; > }; CLAMAGE: I don't find any guarantee that 3 int struct members will have the same offsets as elements of an int array. For example, I don't find a requirement that the alignment of array elements be the same as the alignment of struct members. This example does not even pass the "common initial sequence" test. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com