Skip to main content

IAR Embedded Workbench for Arm 9.70.x

Structure types

In this section:

The members of a struct are stored sequentially in the order in which they are declared—the first member has the lowest memory address.

Alignment of structure types

The struct and union types have the same alignment as the member with the highest alignment requirement—this alignment requirement also applies to a member that is a structure. To allow arrays of aligned structure objects, the size of a struct is adjusted to an even multiple of the alignment.

General layout

Members of a struct are always allocated in the order specified in the declaration. Each member is placed in the struct according to the specified alignment (offsets).

struct First
{
  char c;
  short s;
} s;

This diagram shows the layout in memory:

StructLayout_70percent_02.png

The alignment of the structure is 2 bytes, and a pad byte must be inserted to give short s the correct alignment.

Packed structure types

The __packed data type attribute or the #pragma pack directive is used for relaxing the alignment requirements of the members of a structure. This changes the layout of the structure. The members are placed in the same order as when declared, but there might be less pad space between members.

Note

Accessing an object that is not correctly aligned requires code that is both larger and slower. If such structure members are accessed many times, it is usually better to construct the correct values in a struct that is not packed, and access this struct instead.

Special care is also needed when creating and using pointers to misaligned members. For direct access to misaligned members in a packed struct, the compiler will emit the correct (but slower and larger) code when needed. However, when a misaligned member is accessed through a pointer to the member, the normal (smaller and faster) code is used. In the general case, this will not work, because the normal code might depend on the alignment being correct.

This example declares a packed structure:

#pragma pack(1)
struct S 
{
  char c;
  short s;
};

#pragma pack()

The structure S has this memory layout:

StructLayout_Packed_70percent.png

The next example declares a new non-packed structure, S2, that contains the structure s declared in the previous example:

struct S2
{
  struct S s;
  long l;
};

The structure S2 has this memory layout

StructLayoutCombined_70percent.png

The structure S will use the memory layout, size, and alignment described in the previous example. The alignment of the member l is 4, which means that alignment of the structure S2 will become 4.

For more information, see Alignment of elements in a structure.