6
struct Dummy {
  int x;
  char y;
};

int main() {
  struct Dummy dum;
  dum.x = 10;
  dum.y = 'a';
}

How would be the layout of the structure members on a little endian machine?

Would it be something like this?

  0x1000  +0   +1   +2   +3
         ___________________
    x:  | 10 |  0 |  0 |  0 |     
         -------------------       
    y:  | 'a'|  0 |  0 |  0 |
         -------------------
  0x1000  +4   +5   +6   +7 
Zuzu
  • 3,363
  • 5
  • 27
  • 16
  • 1
    This is fairly compiler dependent. Not only are we dealing with struct alignment and padding, we are also dealing with non-fixed width data types. – Skyler Saleh Mar 27 '11 at 15:15

3 Answers3

8

I think you'll find this question useful. The endianess is usually relevant for a word in the memory, not to the whole structure.

Community
  • 1
  • 1
MByD
  • 135,866
  • 28
  • 264
  • 277
4

Structure layout is a compiler implementation detail, affected by the default packing. Endianness normally only affects the order of the bytes in a structure member value, not the layout. Check the small print in the compiler manual or use sizeof and the offsetof macro to experiment.

The layout you documented in your question is indeed very common for a 32-bit LE compiler.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

The structure members will be in the order declared, with padding inserted as necessary so each field is properly aligned for its type and with padding inserted as necessary at the end such that in an array each subsequent structure is properly aligned and begins immediately after the end of the previous structure. It is also possible (but unlikely) that additional unnecessary padding will be inserted between any two elements or at the end.

Each field itself will be stored as appropriate for the type on the compiler and architecture, e.g. the int 10 would be stored as the bytes 0a 00 00 00 on a normal little-endian machine with 32-bit ints.

Anomie
  • 92,546
  • 13
  • 126
  • 145