Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!shadooby!accuvax.nwu.edu!nucsrl!gore!jacob From: jacob@gore.com (Jacob Gore) Newsgroups: comp.lang.c Subject: Re: struct accessing Message-ID: <470002@gore.com> Date: 28 Jun 89 17:34:48 GMT References: <1545@stl.stc.co.uk> Reply-To: jacob@gore.com (Jacob Gore) Organization: Gore Enterprises Lines: 29 / comp.lang.c / mcdaniel@uicsrd.csrd.uiuc.edu (Tim McDaniel) / Jun 27, 1989 / > In article <470001@gore.com> jacob@gore.com (Jacob Gore) writes: > > #define TOM (&fred_proto.tom - &fred_proto) > > #define DICK (&fred_proto.dick - &fred_proto) > > #define HARRY (&fred_proto.harry - &fred_proto) > > Close, but no cigar. The pointer subtraction yields an error message, > since &fred_proto is of type "struct fred *" and &fred.proto.tom is of > type "int *". I suppose casting one into the other is non-portable? > Suppose, instead, that it was > #define TOM (&fred_proto.tom - &fred_proto.tom) > #define DICK (&fred_proto.dick - &fred_proto.tom) > #define HARRY (&fred_proto.harry - &fred_proto.tom) > > Even if tom is the first int member of a struct fred, and all the int > members are contiguous, it still isn't guaranteed to work. Pointer > subtraction is defined by pANS C only over pointers into the same > array. In particular, a compiler can put an arbitrary number of bytes > of padding between struct members, and such padding wouldn't have to > be a multiple of sizeof(int) bytes long. Why is the padding relevant? The only requirement is that a field's offset is the same for all instances of the struct. -- Jacob Gore Jacob@Gore.Com {nucsrl,boulder}!gore!jacob