4
votes

I have an array of structures defined as below:

struct { int x; char y; } arr[10];

The size of int on my machine is 4 bytes and a char is of 1 byte. I know the structures would be padded internally i.e each element of array will have a size of 8 bytes. But i want to know whether

1) This is because of the alignment requirement of the int-type member in the next array element or

2) Is it because each structure should itself be aligned on a 8-byte boundary because of the requirement of natural alignment on a structure type variable.

To make my point more clear what should be starting address of the first member of array? If it's an 8 byte aligned address as pointed out in the second case, this may be a problem while defining large 2-D arrays like:

int arr[1000][1000];

Here each element of the 2-D array (i.e each 1-D array) should be aligned on a 4000 byte boundary. The machine may not have memory hole to fulfill this memory requirement.

1
Which programming language?Raedwald
Its C. Also if I apply sizeof on a single instance of the struct (not an element of the struct array) defined separately, I get 8 bytes as an answer and not 5 bytes. Why is it so? Does the compiler pad even in the case of a single instance, when the memory is free after the memory occupied by the instance?Maxx.ag

1 Answers

5
votes

I'm not sure I understand the difference between the two options you mention.

Every type in C++ has a natural alignment, of which its size is a multiple. But the alignment is not necessarily equal to the size of the object.

For example, an int typically has a natural alignment of 4 bytes, and a size of 4 bytes.

But while an array of 1000 ints has a size of 4000 bytes, it still only requires a 4-byte alignment.

Compound types (structs and arrays) only require the same alignment as their most-aligned member. An array of 1000 ints only contains objects of one type: int. And that type requires 4-byte alignment, so the array as a whole also only requires 4-byte alignment.

Likewise for your example struct, it has a size of (usually) 8 bytes, but it consists of an int (which requires 4 byte alignment), and a char (which requires 1-byte alignment). The strictest alignment required by any of its members is therefore 4 - and so the struct requires 4-byte alignment