Mail Archives: djgpp/1997/01/23/18:40:52
Josh Anderson asked:
>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.
>
>Thanks in advance,
>Josh
>
Hi Josh,
You could try the following (example is in plain C):
----- CUT HERE -----
#include <stdlib.h>
#include <stdio.h>
#define MAX_ENTRIES 100
typedef struct MyStruct
{
int field1;
char field2[100];
} MyStruct;
main()
{
MyStruct
*dynamic;
int
loop;
/* Allocate the memory */
dynamic = (MyStruct *) malloc(sizeof(MyStruct) * MAX_ENTRIES);
if (dynamic != NULL)
{
/* Do whatever */
for(loop = 0; loop < MAX_ENTRIES; loop++)
{
dynamic[loop].field1 = loop + 1;
dynamic[loop].field2[0] = '\0';
}
/* Release the memory */
free(dynamic);
}
else
{
printf("Could not allocate memory!\n");
}
}
----- CUT HERE -----
Hope this helps
John
________________________________________________________________
Parallax Solutions Ltd. Tel.: 01203 514522
Stonecourt, Fax.: 01203 514401
Siskin Drive, Web : http://www.parallax.co.uk/~johne
Coventry CV3 4FJ Mail: johne AT parallax DOT co DOT uk
________________________________________________________________
Good manners cost nothing, bad manners can cost you everything
________________________________________________________________
- Raw text -