struct accessing
Jacob Gore
jacob at gore.com
Thu Jun 29 03:34:48 AEST 1989
/ comp.lang.c / mcdaniel at uicsrd.csrd.uiuc.edu (Tim McDaniel) / Jun 27, 1989 /
> In article <470001 at gore.com> jacob at 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 at Gore.Com {nucsrl,boulder}!gore!jacob
More information about the Comp.lang.c
mailing list