The type of each member of the structure usually has a default alignment, meaning that it will, unless otherwise requested by the programmer, be aligned on a pre-determined boundary.
gint8
typedef signed char gint8;
A signed integer guaranteed to be 8 bits on all platforms.
and
gint16
typedef signed short gint16;
An unsigned integer guaranteed to be 8 bits on all platforms.
When you have gint16
type of fare_zone
in your structure, the compiler is padding struct _sg64_struct
with 1 byte to align fare_zone
.
So, this is happening with your structure when the fare_zone
is of type gint16
:
struct _sg64_struct
{
SG64_PCSC_TLV_HEADER header; // 2 bytes 4115
gint8 id_perso; // 1 byte 00
gint8 status; // 1 byte 02
gint8 fare_type; // 1 byte 00
gchar pad[1]; <------ // 1 byte 00 (compiler is padding 1 byte to align fare_zone, as short type are 2-byte aligned)
gint16 fare_zone; // 2 byte 0000
gint8 support_type; // 1 byte 0E
gchar loginPerso[15]; // 15 byte 2020202020202020202020202020
};
And that's why support_type
gets 0x0E value instead of 00.
When you have gint8
type of fare_zone
in your structure, the compiler is padding size of struct _sg64_struct
with 1 byte to alignment boundary and doing trailing padding.
struct _sg64_struct
{
SG64_PCSC_TLV_HEADER header; // 2bytes 4115
gint8 id_perso; // 1 byte 00
gint8 status; // 1 byte 02
gint8 fare_type; // 1 byte 00
gint8 fare_zone[2]; // 2 byte 0000 (no alignment required as the char types are 1 byte aligned)
gint8 support_type; // 1 byte 00
gchar loginPerso[15]; // 15 byte 0E2020202020202020202020202020
gchar pad[1]; <------ // Compiler is padding 1 byte to alignment boundary of structure
};
And that's why this structure works.
I would suggest not to map the structure with the sequence of bytes as the alignment of structure members might be vary based on the compiler and underlying platform.
Additional note:
Every modern compiler will automatically use data structure padding depending on architecture. Some compilers even support the warning flag -Wpadded
which generates helpful warnings about structure padding. These warnings help the programmer take manual care in case a more efficient data structure layout is desired.
-Wpadded
Warn if padding is included in a structure, either to align an element
of the structure or to align the whole structure. Sometimes when this
happens it is possible to rearrange the fields of the structure to
reduce the padding and so make the structure smaller.
So, if your compiler supports warning flag -Wpadded
, try compiling your code with it. That will help you in understanding the padding included in a structure by the compiler.