2

If I define a C struct as,

typedef struct
{
  double data[2];
} my_struct;

Is there any possibility that padding would be added to such a structure? Or can I safely assume that sizeof(my_struct) is always 2*sizeof(double) on all systems?

vibe
  • 333
  • 1
  • 9

1 Answers1

3

Compiler implementations are allowed to add any padding in a structure between fields or after the final field.

It probably won't in this case, since you only have one data type, but there's no guarantee that it won't.

If you need to control implementation-specific behavior, many implementations will give you that level of control, such as with #pragma pack, for example.

Even if you don't have that level of control, you can use standard features to at least catch the problem at compile time (C11 or better):

#include <assert.h>
typedef struct { double data[2]; } my_struct;
static_assert(sizeof(my_struct) == sizeof(double) * 2, "I do not like padding");
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953