Why is short 2-byte aligned?

there is a C structure declaration here:

struct align
{
    char c; //1 byte
    short s;//2 bytes
};

In my environment, sizeof (struct align) is 4, and a 1 byte space is between 'char c' and 'short s'. Some say that because the "short" must be aligned by 2 bytes, so the bytes are 1 byte after the "char c". On a 32-bit machine, I know that "int" is better than 4-byte, to prevent two cycles of reading memory, since addresses sent via the address bus between the CPU and memory are a multiple of 4. But "short" is 2 bytes, which is less than 4 bytes, so its address can be any byte in a 4-byte block (except for the last byte).

several of 4 addresses → | 0 | 1 | 2 | 3 |

I mean, the “short” can start with 0, 1 or 2. Everything can be obtained with a 1 read cycle, should not be 0 or 2. In my case, “struct align”, “char c 'can be in 0, "short s" may be 1-2, indentation may be 3.

Why should a 2-byte long short be aligned to 2 bytes?

thank

Update my environment: gcc version 4.4.7, i686, Intel

+4
source share
1 answer

This is because a member is structnot different from one variable of this type, from a machine point of view. Whatever alignment you choose, it applies to both.

For example, if shorttwo bytes long,

struct align
{
    char c;
    short s; // two-byte word
};

short ss; // two-byte word

s 2- (, WORD IA32), "" ss. . , , .

, . ss 4- .

+3

Source: https://habr.com/ru/post/1536211/


All Articles