K
Keith Thompson
CBFalconer said:Keith said:CBFalconer said:Richard Tobin wrote:
Arrays have to be contiguous in memory. No padding bytes may be
inserted between items. The rest follows from that.
Nonsense. Consider:
struct foo {int iv; char ch} arr[N];
A struct foo, on a machine with sizeof int == 4, will be occupy 5
bytes. However, in order to make addressable arrays of these,
sizeof struct foo == 8 (assuming ints need to be aligned modulo
4). I.E. there are 3 padding bytes per item.
But these padding bytes are part of the items, not between them.
sizeof(struct foo) has to be 8 regardless of whether the struct is in
an array. If it's in another struct, the 3 padding bytes have to be
there even if the next item in the struct is a char. Even if it's
just a plain automatic variable, the bytes have to be present and
not used for another object, because you could memcpy() 8 bytes
to it.
If you think about it for about 2 1/4 secs I am sure you can come
up with a struct definition that puts the padding in the middle.
Don't forget that ALL items have to be aligned.
So what? The point is that padding may be inserted between members of
a struct, but padding *may not* be inserted between elements of an
array.
Any padding in struct foo, whether it's between members, after the
last member, or both, is *part of struct foo*.
Given
struct foo arr[N];
any padding between arr[0] and arr[1] is guaranteed to be nonexistent.
If this weren't the case, then the common idiom
sizeof arr / sizeof arr[0]
to determine the length of an array would not work.
The statement that you disputed, quoted above, was
Arrays have to be contiguous in memory. No padding bytes may be
inserted between items. The rest follows from that.
That statement was perfectly correct.
No, because you are considering the structure to be a monolith,
while I am looking at it as consisting of some sort of combination
of items, possibly separated by padding. If your quoted line said
"between array items" I would have to agree.
I am considering the structure to be an object, which is exactly what
it is. It's perfectly obvious from the context that the phrase
"between items" means "between elements of an array", since the
previous sentence talked about arrays, not about the (irrelevant in
this context) internals of their elements.
[...]It really is counting angels on pinheads, and not important.
It really is getting the description right, and it's very important.
In any case, I think we're all in agreement that there can be no
padding between elements of an array. I'm sure you know that, but
what you wrote upthread led me to think that you didn't. I presume
the problem was with the words, not with the concepts.
If you'll re-read what you wrote upthread with an open mind, I think
you'll see that someone could easily have inferred from your words
that it's possible for a structure with a size of 5 bytes to occupy 8
bytes if it's an element of an array.