home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!news.funet.fi!hydra!klaava!wirzeniu
- From: wirzeniu@klaava.Helsinki.FI (Lars Wirzenius)
- Newsgroups: comp.lang.c
- Subject: Re: Variable length records
- Message-ID: <1992Jul25.091702.15993@klaava.Helsinki.FI>
- Date: 25 Jul 92 09:17:02 GMT
- References: <24137@castle.ed.ac.uk> <rbjmzg-.gurgle@netcom.com>
- Organization: University of Helsinki
- Lines: 64
-
- gurgle@netcom.com (Pete Gontier) writes:
- >typedef struct
- >{
- > short count;
- > float data[ ];
- >}
- >foo;
- >
- >I refer to the second member as an "open array." Its behavior is this:
- > o it may appear only as the last member of a structure
- > o it does not contribute to the value returned by sizeof(foo)
- > o it may be addressed, of course, with an arbitrary index
-
- Are there any particular reasons to not use
-
- typedef struct {
- short count;
- float data[1];
- } foo;
-
- (and similar over-allocation and using "too large" indexes) instead?
- This version only assumes that there won't be any problems for accessing
- elements outside the data array.
-
- And, except for a minor gain in convenience for allocation and
- deallocation, is either of these preferable to
-
- typedef struct {
- short count;
- float *data;
- } foo;
-
- (and allocating the memory for data separately) which _is_ ANSI
- compliant?
-
- >I got worried about its portability so I paged through some manuals.
- >Both major C compilers for the Mac support it. Turbo C and Microsoft
- >C for the PC support it. According to Harbison and Steele, ANSI does
- >*not* support it. And from experience I know that AT&T cfront 2.1 (the
- >most common "standard" for C++) does not support it. I'm a little bit
- >suprised that it's not in the ANSI standard, but after my research I
- >felt it was common enough that I'd use it with impunity. And now I've
-
- >just checked with 'gcc' 1.39, and it doesn't like it. Perhaps 2.x does.
-
- My gcc 2.2.2 under Linux doesn't seem to support it, at least with the
- default options:
-
- foo.c:3: field `data' has incomplete type
-
- >Not knowing about records simply means you have to implement it yourself.
- >There are no problems, as long as your compiler cooperates, with UNIX.
-
- Actually, I don't think any special compiler cooperation is required.
- To output the last version above to a file you do:
-
- fwrite(&foo.count, sizeof(foo.count), 1, outfile);
- fwrite(foo.data, sizeof(float), foo.count, outfile);
-
- (with error checking, of course) and similarly to read it. (You might
- wish to use text files, to achieve better data portability.)
-
- --
- Lars.Wirzenius@helsinki.fi
-