1

I am trying to understand how exactly structures work in C. More precisely, the size of a structure.

When I print the size of the following structure:

struct Test {
   char tab[14];
};

I have the output 14.

But the size of

    struct Test2{
         uint16_t  a;
         uint16_t  b;
         uint16_t   c;
         uint64_t  d; 
    };

is equals to 16.

I read in a previous post that there is a "padding added to satisfy alignment constraints". Then why this padding isn't apply to the first example ?

Julien
  • 91
  • 8
  • 1
    you might want to look at the pack pragma directive: https://stackoverflow.com/questions/3318410/pragma-pack-effect – bruceg Apr 04 '19 at 21:04
  • Characters (single byte types) don't need alignment; only data types longer than a single byte need alignment. Also, remember that padding isn't added to anger programmers. It is added to give better performance when accessing the members of a structure. Interfere with the compiler's best judgement at your own risk. – Jonathan Leffler Apr 04 '19 at 21:07

2 Answers2

3

Padding is not allowed to be applied in the middle of an array (else pointer arithmetic would break). So all the elements of tab are contiguous.

Furthermore the address of tab[0] needs to the be the same as the address of the corresponding instance of Test; i.e. padding is not allowed at the beginning of a struct.

There could, however, be padding at the end. In your case though, there isn't.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

Padding has to do with the alignment at which an object must be arranged. Your first structure only has a char member, and so it can be positioned at any address. Thus there is no padding necessary, since the next element in an array of such beasts may follow directly after.

For other structures that contain members with different alignment constraints, things become more complicated. They must be padded internally to accomodate different alignment requirements, and there can be padding at the end, if the overall alignment is at odds with the size.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • Thank you for your answer. Is there anyway to disable the padding ? – Julien Apr 04 '19 at 21:01
  • 1
    @Julien : supression of padding is compiler specific by command line option for _all_ structs or by `#pragma` or type attribute in the code. Refer to your compiler documentation. – Clifford Apr 04 '19 at 21:04
  • This is exactly what I was looking for ! Is it common to use #pragma? – Julien Apr 04 '19 at 22:14