** help...

Gordon Burditt gordon at sneaky.UUCP
Sun Sep 2 14:37:41 AEST 1990


>>[...] the value produced [by sizeof(int *[xL]) if it were legal] would be the
>>same as (xL * sizeof(int *)), so malloc wouldn't know the difference.
>
>This is not guarenteed true for all types by anything I can find in K&R 2.
>The crux of the potential health hazard comes with the definition of
>sizeof, which K&R2 says (section 6.3) gives a size_t result equal to the
>size of the specified object or type in bytes. Nothing here guarentees
>that the *end* of the object will be such that another object straight
>after it in memory (which is what the multiplication implies) will be
>correctly aligned. Many structs would give appropriately odd lengths;
>I'm sure you don't need examples.

ANSI C standard 3.3.3.4 "The sizeof operator":
...
Another use of the sizeof operator is to compute the number of members
in an array:
	sizeof array / sizeof array[0]

end quote


Set '=' to mean mathematical equation, not C assignment.
Set '/' to mean C integer division.

If you have an array of structs, then:
    number_elements = sizeof array / sizeof array[0]
If the array is some structs plus external padding (the total padding in the
whole array),
    sizeof array = number_elements * sizeof struct foo + external_padding_bytes
Substituting,
    number_elements = ((number_elements * sizeof struct foo) + 
	external padding bytes) / sizeof struct foo

    number_elements = number_elements + 
	external_padding_bytes / sizeof struct foo

    0 = external_padding_bytes / sizeof struct foo

If you make the dimension of the array much larger than sizeof struct foo,
then the total number of external padding bytes in the array must be
much less than one per array element.

This pretty much kills the alignment argument.  Sizeof must include
trailing padding and internal padding in a structure.  And there
cannot be any *LEADING* padding for other reasons.

					Gordon L. Burditt
					sneaky.lonestar.org!gordon



More information about the Comp.lang.c mailing list