0

The following code gives the result sizeof(t1)=16 sizeof(t2)=16 I would have expected sizeof(t2)=12 because sizeof(fpos_t)=8 and sizeof(int)=4. Can someone explain this?

int main()
{
    typedef struct {
        fpos_t fpos;
        char* s;
        int a;
    } t1;
    typedef struct {
        fpos_t fpos;
        int a;
    } t2;
    t1 it1;
    t2 it2;
    printf("sizeof(t1)=%d sizeof(t2)=%d ", sizeof(t1), sizeof(t2));
    return 0;
}
Clifford
  • 88,407
  • 13
  • 85
  • 165
Alfred
  • 139
  • 2
  • 12

2 Answers2

0

For alignment reasons, compiler is free to insert padding. That means the size of a struct is not necessarily equal to the sum of size of individual members. This is explicitly allowed by the C standard.

The only place where padding is not allowed at the start of a struct i.e. before the first member.

From C11 draft, 6.7.2.1:

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

(emphasis mine).

P.P
  • 117,907
  • 20
  • 175
  • 238
0

Most computers now in days only allow allocation at "words" (aka 8 bytes, aka 64 bits) at a time. It's called padding.

Think of it as hotel rooms. Regardless if you have 1 or 2 people (chars) staying in the same room (memory location), the room will be the same size.

Dellowar
  • 3,160
  • 1
  • 18
  • 37