calculating the size of structure

前端 未结 3 1010
南方客
南方客 2021-01-26 10:09

I was going through the concept of structure member alignment and structure padding concept when I found that the size of this struct ...

struct nod         


        
3条回答
  •  盖世英雄少女心
    2021-01-26 11:02

    Data structure alignment.

    Described wonderfully here.

    Suppose you have this structure:

    struct  {
        char a[3];
        short int b;
        long int c;
        char d[3];
        };
    

    Now, you might think that it ought to be possible to pack this structure into memory like this:

    +-------+-------+-------+-------+
    |           a           |   b   |
    +-------+-------+-------+-------+
    |   b   |           c           |
    +-------+-------+-------+-------+
    |   c   |           d           |
    +-------+-------+-------+-------+
    

    But it's much, much easier on the processor if the compiler arranges it like this:

    +-------+-------+-------+
    |           a           |
    +-------+-------+-------+
    |       b       |
    +-------+-------+-------+-------+
    |               c               |
    +-------+-------+-------+-------+
    |           d           |
    +-------+-------+-------+
    

    In the ''packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will ''pad'' the structure (as if with extra, invisible fields) like this:

    +-------+-------+-------+-------+
    |           a           | pad1  |
    +-------+-------+-------+-------+
    |       b       |     pad2      |
    +-------+-------+-------+-------+
    |               c               |
    +-------+-------+-------+-------+
    |           d           | pad3  |
    +-------+-------+-------+-------+
    

    This post explained how padding is done, not why it is done. Please refer haccks' answer for why it is done.

提交回复
热议问题