Jason Curl wrote:
Hello,
Does the C standard specify (and if so, how, or possibly a reference to
the standard - I don't have a copy). I am also assuming that CHAR_BIT is
8 (for Posix systems)
a) How elements in a union overlap
All the union's elements start at the same address.
More formally, a pointer to the union can be converted
to a pointer to any of its elements, and vice versa.
b) limitations on how elements in a structure are padded
Padding may appear after any element of the struct.
(People often say "Between any elements, and at the end
of the struct," but that's just a longer way of saying
the same thing.) The struct's first element starts at
the struct's address; more formally, a pointer to the
struct can be converted to a pointer to its first element,
and vice versa.
This will help me in writing (hopefully) portable C code that can
communicate across different architectures, that may be faster and more
memory efficient than copying from one buffer to another.
Or is the only practical way to memcpy() taking into account endianness
of the machine into a "char *buffer"?
memcpy() might not be enough. For example, you may
want to communicate a `long' value, but `long' on machine A
is 32 bits while on machine B it's 64. Or perhaps you want
to move a `long double' value between a machine were it is
actually more precise than plain `double' and a machine
where it's really just a plain `double' with a different name.
Mere memcpy() cannot reconcile such differences.
What's usually needed is a careful specification of the
external format -- the way the information looks "on the
wire" or "in the file." Then for each machine you write a
pair of functions (or a set of pairs): one to convert the
machine's idiosyncratic internal data representation to the
external form, and one to digest the external form and convert
it to the internal representation. A visit to someplace like
wotsit.org may give you some ideas about how to specify an
external format that has a reasonable chance at portability:
study the way JFIF or WAV files (for example) are described,
and see if you can steal, er, "be inspired by" their techniques.
--
Eric Sosman
es*****@acm-dot-org.invalid