Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Is the offset of struct always the first byte?


Asked by Julie Ali on Dec 12, 2021 FAQ



I know that &<struct> does not always point at the first byte of the first field of the structure, I can account for that later. How about the standard offsetof () macro (in stddef.h)?
Thereof,
Structures can contain padding to ensure that fields are correctly aligned and that the structure itself is correctly aligned. The following diagram shows an example of a conventional, nonpacked structure. Bytes 1, 2, and 3 are padded to ensure correct field alignment. Bytes 11 and 12 are padded to ensure correct structure alignment.
Moreover, The 'p' format character encodes a “Pascal string”, meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow.
Also Know,
The most common types used for that purpose are bytes and bytearray, but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes object. The module defines the following exception and functions:
Keeping this in consideration,
In the example structure, the second byte of the int container has two bits allocated to x, and six bits unallocated. The compiler allocates a char container starting at the second byte of the previous int container, skips the first two bits that are allocated to x, and allocates two bits to y.