Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!samsung!olivea!uunet!overload!dillon From: dillon@overload.Berkeley.CA.US (Matthew Dillon) Newsgroups: comp.sys.amiga.programmer Subject: Re: Dynamic struct's Message-ID: Date: 8 May 91 20:46:10 GMT References: <52955@nigel.ee.udel.edu> Organization: Not an Organization Lines: 64 In article <52955@nigel.ee.udel.edu> DA3721A@acad.drake.edu writes: >I am currently working on programming a fairly simple database in C. The >program will allow the user to specify the number of fields in the database >and their names. My question is: How does one dynamically declare a struct >for accessing the correct number of fields? In other words, rather than doing > > struct { > int field1; > char field2; > int field3; > } record; > >I would like to do something like > > struct { > int field1; > char field2; > . > . > . > int fieldx; > } record; I generally do the following: struct { HeadInfo rc_Info; int rc_fields[XX]; } record; Where XX can be 0, 1, or MAXFIELDS depending on how you implement the structure. For example, if you use MAXFIELDS then you would allocate the structure like this: #include struct record *rec = malloc(offsetof(struct record, rc_fields) + sizeof(rec->rc_fields[0]) * NumFields); If you use XX = 0 (int rc_fields[0]), assuming the compiler allows it, you can allocate the structure like this: struct record *rec = malloc(sizeof(struct record) + sizeof(rec->rc_fields[0]) * NumFields); If you use XX = 1 (int rc_fields[1]), which the compiler had better allow, you can allocate the structure like this: struct record *rec = malloc(sizeof(struct record) + sizeof(rec->rc_fields[0]) * (NumFields - 1)); Once allocated, you can initialize/use up to NumFields of the array rc_field. I included the HeadInfo type just to show you how to allocate nominal structures with extensions. > > Thanks in advance, > David Aschbrenner -Matt -- Matthew Dillon dillon@Overload.Berkeley.CA.US 891 Regal Rd. uunet.uu.net!overload!dillon Berkeley, Ca. 94708 USA