Xingbo G said:
The question 2.11 of C FAQ describes how we can read/write structures
from/to data files. However, there is a sentence that doesn't make
sense to me - <What's important is that fwrite receive a byte pointer,
not a structure pointer.> Does it apply to pre-ANSI C? Or could you
explain what a byte pointer is?
And, a more simple question - why aren't the numbers in the C FAQ
continuous? Like it jumps from 1.1 to 1.4 and from 1.7 to 1.11?
Thanks.
Data types have different alignment requirements. A pointer
to a data type that has a stricter (wider) alignment than
char may be represented differently than a char pointer.
For example, suppose data type "double" has 8-byte alignment.
A double pointer would then always have the 3 least significant
bits zero (the pointer value is always a multiple of 8). Thus,
since the double pointer always has 3 zero bits, it is alright
to truncate the value to remove those bits (unsigned right
shift 3 bits).
Now then, if the struct pointer contains a double, then the
struct alignment is also (at least) a multiple of 8 bytes and
a pointer to the struct will be represented differently than a
char pointer. You would need an explicit cast to (char *) to
convert the pointer to a value that is compatible with what
the function is expecting. The cast to (char*) would implicitly
shift left 3 bits the double pointer value.
Note: Only the compiler knows for sure how to convert an aligned
pointer to a char pointer (and vice versa), so don't try shifting
the value. Let the cast do it.
Most compiler implementations don't bother with shifting
out the alignment bits, so a double pointer and a char
pointer have the same representation and the same number
of significant bits. Thus, non-conforming code that depends
on this behavior is broken, but will work most of the time.
When the code is ported to a compiler that performs the
alternative aligned pointer representations, it will break.
--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS for FREE!