Why doesn’t C++ make the structure tighter?

Class and struct members are required by the standard to be stored in memory in the same order in which they are declared. So in your example, it wouldn’t be possible for d to appear before b. Also, most architectures prefer that multi-byte types are aligned on 4- or 8-byte boundaries. So all the compiler … Read more

What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?

See this page on the ARC project for a survey of solutions, there is a trade-off between implementation complexity/time and optimality, but there is a wide range of algorithms to choose from. Here’s an extract of the algorithms: First-Fit Decreasing Height (FFDH) algorithm FFDH packs the next item R (in non-increasing height) on the first … Read more

Structure padding and packing

Padding aligns structure members to “natural” address boundaries – say, int members would have offsets, which are mod(4) == 0 on 32-bit platform. Padding is on by default. It inserts the following “gaps” into your first structure: struct mystruct_A { char a; char gap_0[3]; /* inserted by compiler: for alignment of b */ int b; … Read more