Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: another simple c question

Author: Dann Corbit

Date: 10:30:19 07/21/04

Go up one level in this thread


On July 21, 2004 at 06:16:10, Daniel Shawul wrote:

>
>Isn't the size of a struct the sum of the sizes of its members.
>
>but for this struct sizeof(HASH_E) gives me 16 when i expect 14
>
>struct HASH_E
>{
>	HASHKEY checksum;
>	char     from;
>	char     to;
>	short    eval;
>	unsigned char    depth;
>	unsigned char    entry_threat_promote_seq;
>};
>
>daniel

From the C FAQ:

2.12:	My compiler is leaving holes in structures, which is wasting
	space and preventing "binary" I/O to external data files.  Why?
	Can I turn this off, or otherwise control the alignment of
	structure fields?

A:	Those "holes" provide "padding", which may be needed in order to
	preserve the "alignment" of later fields of the structure.  For
	efficient access, most processors prefer (or require) that
	multibyte objects (e.g. structure members of any type larger
	than char) not sit at arbitrary memory addresses, but rather at
	addresses which are multiples of 2 or 4 or the object size.

	Your compiler may provide an extension to give you explicit
	control over struct alignment (perhaps involving a #pragma; see
	question 11.20), but there is no standard method.

	See also question 20.5.

	References: K&R2 Sec. 6.4 p. 138; H&S Sec. 5.6.4 p. 135.

2.13:	Why does sizeof report a larger size than I expect for a
	structure type, as if there were padding at the end?

A:	Padding at the end of a structure may be necessary to preserve
	alignment when an array of contiguous structures is allocated.
	Even when the structure is not part of an array, the padding
	remains, so that sizeof can always return a consistent size.
	See also question 2.12 above.

	References: H&S Sec. 5.6.7 pp. 139-40.

2.14:	How can I determine the byte offset of a field within a
	structure?

A:	ANSI C defines the offsetof() macro in <stddef.h>, which lets
	you compute the offset of field f in struct s as
	offsetof(struct s, f).  If for some reason you have to code this
	sort of thing yourself, one possibility is

		#define offsetof(type, f) ((size_t) \
			((char *)&((type *)0)->f - (char *)(type *)0))

	This implementation is not 100% portable; some compilers may
	legitimately refuse to accept it.

	References: ISO Sec. 7.1.6; Rationale Sec. 3.5.4.2; H&S
	Sec. 11.1 pp. 292-3.




This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.