Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!mcvax!ukc!its63b!xsimon From: xsimon@its63b.ed.ac.uk (Simon Brown) Newsgroups: comp.lang.c Subject: Re: Arrays of Unknown Length in Structures (and sizeof) Message-ID: <668@its63b.ed.ac.uk> Date: Sat, 3-Oct-87 15:45:58 EDT Article-I.D.: its63b.668 Posted: Sat Oct 3 15:45:58 1987 Date-Received: Wed, 7-Oct-87 06:22:34 EDT References: <243@mit-prep.ARPA> <1044@ius1.cs.cmu.edu> Reply-To: xsimon@its63b.ed.ac.uk (Simon Brown) Organization: Computer Science Department, Edinburgh University Lines: 55 In article <1044@ius1.cs.cmu.edu> edw@ius1.cs.cmu.edu (Eddie Wyatt) writes: >> struct STRUCT_FOO >> { >> int one; >> int two; >> int open[]; >> }; >> >> foo_p = malloc(sizeof (struct STRUCT_FOO) + (7 * sizeof (int))); >> >> for (i = 0; i < 7; ++i) >> foo_p->open[i] = i * 100; >> >> As far as I'm concerned, if this isn't kosher, it should be! > > Let me give you a reason of why this should not be "kosher". > I don't think it is required in C that the fields in a structure > be phyically ordered in the same ordering they are declared. > Hence any of the 6 permutations of the fields you describe > are valid for phyical offset orderings (ie open could have > an offset of 0, two could have an offset of 0 and one could > have an offset of 0 + sizeof(int)). This would wreak havoc!! > Umm, but what about the System V "msgbuf" type, used for the msg IPC system calls? This has type struct msgbuf { long mtype; char mtext[1]; } and is intended to be used as a template type, by malloc()'ing space of whatever message buffer size is required, with something like msg = (struct msgbuf *)malloc(sizeof(struct msgbuf) + NBYTES); which results in a message with bytes mtext[0] ... mtext[NBYTES]. If a compiler is free to alter the order of occurence of the fields of a structure, then this is no longer portable. (Yes, I realize that this has nothing to do with the C language as such, but it can't be just ignored!). (BTW, certainly I'd much prefer something like "char mtext[]" or even "char mtext[0]", but it seems that zero-sized types are not too popular with compilers, more's the pity :-(). %{ Simon. %} -- ---------------------------------- | Simon Brown | UUCP: seismo!mcvax!ukc!{lfcs,its63b}!simon | Department of Computer Science | JANET: simon@uk.ac.ed.{lfcs,its63b} | University of Edinburgh, | ARPA: simon%lfcs.ed.ac.uk@cs.ucl.ac.uk | Scotland, UK. | or simon%its63b.ed.ac.uk@cs.ucl.ac.uk ---------------------------------- or simon%cstvax.ed.ac.uk@cs.ucl.ac.uk "Life's like that, you know"