Want More information about structure padding

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KarthikB
    New Member
    • Sep 2007
    • 1

    Want More information about structure padding

    Hello All,
    Could anybody explain about padding concept used in structures in C language?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    It is efficient for data to be lined up on boundaries that match the register size of the propcessor. This is called word boundary. For a 32-bit chip, 32-bits of data can be moved from memory to the chip register in one operation.

    The compiler knows this so iot attempts to linbe things up on word boundaries.

    Take this struct:
    [code=c]
    struct Example
    {
    int a;
    char b;
    int c;
    };
    [/code]

    It would be efficient if a and c were on 32 bit boundaries. To do that the compile may add three pad bytes after b to force c to a 32-bit boundary.

    If you do a sizeof(Example) and a sizeof(a) + sizef(b) + sizeof(c) and get different answers, you have enountered padding.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      If you're worried about (internal) padding, order your struct/class data members
      from strictest to least strict alignment order, i.e. doubles first, ints next, chars
      last.

      kind regards,

      Jos

      Comment

      Working...