Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!mcvax!diku!thorinn From: thorinn@diku.UUCP (Lars Henrik Mathiesen) Newsgroups: comp.lang.c Subject: Re: Re: Arrays of Unknown Length in Structures (and sizeof) Message-ID: <3453@diku.UUCP> Date: Wed, 7-Oct-87 10:36:23 EDT Article-I.D.: diku.3453 Posted: Wed Oct 7 10:36:23 1987 Date-Received: Wed, 14-Oct-87 04:50:20 EDT References: <243@mit-prep.ARPA> <1044@ius1.cs.cmu.edu> <668@its63b.ed.ac.uk> Organization: DIKU, U of Copenhagen, DK Lines: 43 In article <668@its63b.ed.ac.uk> xsimon@its63b.ed.ac.uk (Simon Brown) writes: >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]. Just to note (again) that this may allocate space for up to NBYTES + sizeof(long) bytes: The structure size will be rounded to the alignment of a long for use in arrays - on most machines this will be stricter than sizeof(char), typically sizeof(long). If you really care about those "wasted" bytes, you can use a "portable" trick like this: struct msgbuf { long mtype; union mu { char mt[1]; double manon; } mu; }; #define mtext mu.mt #define MSGBUFBASE (sizeof(struct msgbuf) - sizeof(double)) msg = (struct msgbuf *)malloc(MSGBUFBASE + NBYTES); But given a structure like struct msgbuf { long mtype; char mflags, mtext[1] }; the former trick would force a stricter alignment on mtext than "necessary", so you would "have to" be unportable and write something like #define MSGBUFBASE (sizeof(msgbuf) - LONGALIGN + CHARARRAYALIGN) By the way, is there anything in the various standards that says whether the alignment of a double (or float) has to be the at least as strict as that of any other datatype? Ditto for sizeof? If not, the first trick has to be fixed. -- Lars Mathiesen, DIKU, U of Copenhagen, Denmark [uunet!]mcvax!diku!thorinn Institute of Datalogy -- we're scientists, not engineers.