user1396736
user1396736

Reputation: 39

struct padding array

If I have a struct like this:

struct { 
       int a; 
       int b;
       int values[20];
       }

It will have any kind of padding?

I've searched about this matter, but all the information I've found is padding between different data types.

Upvotes: 2

Views: 447

Answers (2)

supercat
supercat

Reputation: 81115

I think the only padding the standard would permit in that scenario would be padding that was common to all int variables. Although it is typical for an int to make use of all the bits that are present in the unsigned char memory locations it overlays, it is not required. Some digital signal processors have accumulators with non-power-of-two lengths like 36, 40, or 48 bits (the idea being that one will often want to add together a bunch of 32-bit numbers whose sum would exceed 32 bits; an accumulator bigger than 32 bits is needed, but a 64-bit accumulator would be massive overkill). A DSP with a 16-bit memory bus may be able to read and write char values from memory, but require a particular alignment for everything else. If such a DSP had a 40-bit accumulator, such a device could store its int type as six bytes, one of which would be unused (I'd think it more likely that such a device would use a 32-bit int type and perhaps offer a 40-bit short long or something for cases where an int wasn't quite enough, but a 40-bit int would be "legal").

In general, the standard requires that no type may require alignment which is larger than its size, and an array of any type, at least within a structure, has the same alignment requirement as the underlying type (some implementations may have special alignment requirements for statically-allocated arrays, such as requiring that any such arrays that are smaller than a page in size must be placed so as not to cross page boundaries unless marked with a #pragma or other directive indicating otherwise, but the standard is blind to such requirements since their only possible effect would be to reduce how many variables a program could declare without running out of memory).

Upvotes: 1

user529758
user529758

Reputation:

It will have any kind of padding?

I think padding is something implementation-defined. A reasonable explanation, however, would be that it won't, since all the members have to be aligned for the same number of bytes. This, indeed, is true on my Mac (OS 10.7.5) with GCC:

enter image description here

(The size of the struct is 88 bytes: 4 + 4 + 20 * 4, so there's no padding.)

Upvotes: 1

Related Questions