HP C Programmer's Guide (92434-90009)

Chapter 2 33
Storage and Alignment Comparisons
Aligning Structures Between Architectures
Aligning Structures Between Architectures
Differences in data type alignment can cause problems when porting code or data between
systems that have different alignment schemes. For example, if you write a C program on
the Series 300/400 that writes records to a file, then read the file using the same program
on a Series 700/800, it may not work properly because the data may fall on different byte
boundaries within the file because of alignment differences.
Three methods can be used for aligning data within structures so that it can be shared
between different architectures.
Use only ASCII formatted data. This is the safest method, but has negative
performance and space implications.
Use the HP_ALIGN pragma, which is available on most HP-UX HP C compilers. It forces
a particular alignment scheme, regardless of the architecture on which it is used. See
"The HP_ALIGN Pragma" section for a detailed description of this pragma.
Define platform independent data structures using explicit padding.
To illustrate the portability problem raised by different alignments, consider the following
example.
#include stdio.h
struct char_int
{
char field1;
int field2;
};
main (void)
{
FILE *fp;
struct char_int s;
fp = fopen("myfile", "w");
fwrite(s, sizeof(s), 1, fp);
}
The alignment for the struct that is written to myfile in the above example is shown in
the following diagram.