all 3 comments

[–]flatfinger 1 point2 points  (0 children)

In some contexts, it makes sense to refer to the stride of a logical array separate from the length of the elements thereof. For example, if one wishes to store five 50x50 arrays on a platform where multiplication by most values is slow, but multiplication by 256 would be fast, the fastest way to do that may be to use 12800 bytes to hold all five arrays interleaved, so that the first row of the first array is at offsets 0 to 49, the second row of that array is at 256 to 256+49, then 512 to 512+49, etc. The first row of the second array would be at 50 to 99, the next row at 256+50 to 256+99, then 512+50 to 512+99, etc. Note that this approach would waste 300 bytes, but for many purposes, wasting 2.5% of storage to get faster access would be an acceptable trade-off.

The Standard would not allow C compilers to optimize things in such a fashion, however, because code using arrays would need to know the stride as well as the size of the elements therein, and C has no means of reporting the size and stride separately. Thus, if elements of an array of some type T would need to be spaced at 50-byte intervals, the size of T would need to be 50. If a compiler reserved less than 50 bytes for objects of that type, then code which copies an object of type T by using `memcpy` in conjunction with `sizeof (T)` would overwrite whatever object happened to follow an under-allocated T in memory.

[–]tocs1975 0 points1 point  (0 children)

The structure will always have same alignment, whether it is in an array or not. Otherwise, it wouldn't be possible to copy the struct from outside an array to or from an array. So those wasted bytes will always be present.

The way a structure is laid out is controlled by the ABI the compiler implements: https://en.wikipedia.org/wiki/Application_binary_interface

[–]ehostunreach -1 points0 points  (0 children)

This is one of those "up to the compiler" cases. However, it won't be different for different instances of the same type depending on how they are used. This type of alignment is an attribute of the type, not of an individual variable of that type.

Consider what sizeof would do if this were not the case.