Re: locating an array
On Feb 16, 10:37 pm, r...@zedat.fu-berlin.de (Stefan Ram) wrote:
"Charles Arnett" <carn...@instrulab.com> writes:
I have a structure composedx of floats and strings. I want a
dummy array that is the same length starting at the same
address. I do this so I cann access the individual bytes of
the structure.
I hope that there are not too many locations
with undefined behavior below, and that it is
always possible to align a =BBt*=AB at the address
of an =BBs*=AB:
#include <iostream>
#include <ostream>
struct s { float a, b, c; };
struct t { char a[ sizeof( s )]; };
int main()
{ s s0;
t * t0( reinterpret_cast< t* >( &s0 ));
::std::cout << sizeof( t0->a );
}
This seems more complicated than necessary, as well as
unnecissarily introducing undefined behavior. If the goal is
just to look at the individual bytes in an object:
template< typename T >
void
dump( std::ostream& dest, T const& obj )
{
unsigned char const*p
= reinterpret_cast< unsigned char const* >( &obj ) ;
for ( size_t i = 0 ; i != sizeof( obj ) ; ++ i ) {
if ( i != 0 ) {
dest << ' ' ;
}
dest << HexFmt( 2 ) << static_cast< int >( p[ i ] ) ;
}
}
will do the trick, with no undefined behavior. (This can easily
be dressed up in a class, with an operator<<, and a free
function for type deduction, to make it easier to use.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34