From: "John M. Aldrich" Newsgroups: comp.os.msdos.djgpp Subject: Re: Dynamic Arrays Date: Mon, 20 Jan 1997 21:26:58 -0800 Organization: Two pounds of chaos and a pinch of salt Lines: 74 Message-ID: <32E453A2.FA3@cs.com> References: <01bc072e$33eb9b20$ee038cd0 AT wahander> Reply-To: fighteer AT cs DOT com NNTP-Posting-Host: ppp211.cs.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Josh Anderson wrote: > > I know this is a stupid question, but how do you create a dynamic array of > a bunch of structs? I only need to set the size of the array at init time. > And then free the memory at exit. Any basic C textbook should explain how to do this. It's a standard part of learning the language. A detailed explanation would be more appropriate to one of the C newsgroups (comp.lang.c for example), but I've broken this rule in the past and I will continue to do so in the future. :) If you want to create an array of _fixed_ size at initialization, then the task is extremely simple. First, define your struct. Then create a pointer to that struct type and malloc the appropriate amount of memory. You can then access the pointer exactly like you would an array. When you are ready to exit, just call free() with the original pointer. Example code: #include #include #include struct stuff { int id; char name[20]; char type; time_t date_in; time_t date_out; }; int main( void ) { struct stuff *List; int num_recs, i; printf( "How many records? " ); scanf( "%d", &num_recs ); List = (struct stuff *) malloc( num_recs * sizeof(struct stuff) ); if ( List == NULL ) { fprintf( stderr, "Fatal error: could not allocate %d bytes.\n", num_recs * sizeof(struct stuff) ); exit( 1 ); } for ( i = 0; i < num_recs; i++ ) { get_record( List[i] ); do_stuff( List[i] ); } printf( "All done, thanks.\n" ); free( List ); return 0; } If you want to make the entire list dynamic, i.e.; its size can change during runtime, then you need a much more complex algorithm, but again it's something that's in every C textbook I've ever seen. If you really still need help, email me in private and I'll send you more samples. Good luck! -- --------------------------------------------------------------------- | John M. Aldrich, aka Fighteer I | fighteer AT cs DOT com | | "Starting flamewars since 1993" | http://www.cs.com/fighteer | | *** NOTICE *** This .signature is generated randomly. | | If you don't like it, sue my computer. | ---------------------------------------------------------------------