Data structure alignment: Difference between revisions

Content deleted Content added
m Problems: link
Add concrete example
Line 74:
Although C and C++ do not allow the compiler to reorder structure members to save space, other languages might. It is also possible to tell most C and C++ compilers to "pack" the members of a structure to a certain level of alignment, e.g. "pack(2)" means align data members larger than a byte to a two-byte boundary so that any padding members are at most one byte long. Likewise, in [[PL/I]] a structure may be declared <code>UNALIGNED</code> to eliminate all padding except around bit strings.
 
One use for such "packed" structures is to conserve memory. For example, a structure containing a single byte (such as a char) and a four-byte integer (such as uint32_t) would require three additional bytes of padding. A large array of such structures would use 37.5% less memory if they are packed, although accessing each structure might take longer. This compromise may be considered a form of [[space–time tradeoff]].
 
Although use of "packed" structures is most frequently used to conserve [[memory space (computational resource)|memory space]], it may also be used to format a data structure for transmission using a standard protocol. However, in this usage, care must also be taken to ensure that the values of the struct members are stored with the [[endianness]] required by the protocol (often [[network byte order]]), which may be different from the endianness used natively by the host machine.