C (268/301)

From:andrewmarkwell
Date:17 Aug 99 at 16:48:31
Subject:Re: Structure Arrays

From: andrewmarkwell@ukonline.co.uk

>From: Christian Hattemer <Chris@heaven.riednet.wh.tu-darmstadt.de>
>
>Hi,
>
>I think I've found an easier solution for the problem I had with dynamic
>structs. I'm going to pass in the sizeof() of the whole struct and all
>offsets with offsetof().
>
>The only problem left is: How do I create an array of structs dynamically?
>I'm currently planing to get two blocks of mem, one for the structs and one
>for the pointers to them. Then I would fill out the pointer table starting
>with the address of the structs area, increased by 4 for each pointer.
>
>Is this a good way to create such an array?
>

No problem, I've done similar things myself...

If you use C++, then it's better to use the 'new' operator.

size=100; // or whatever
MyStruct *ptr=new MyStruct[x];

Or using Exec:

MyStruct *ptr;
size=100;
ptr=(MyStruct*)AllocMem(100*sizeof(MyStruct), MEMF_PUBLIC)

You don't need a separate array of pointers as both these functions allocate sequential memory, so you can access them just like an array of MyStruct's.

eg:

ptr[6]=anotherMyStruct;

If you really want a pointer table, then allocate an array of 'size' amount of MyStruct's, then use a counting loop to record its exact pointer - although I can't think of any reason why you'd want to do this.

If you want to add further records later then you'll need to allocate a new area of memory of size equal to new records added to the existing... copy the existing data using memcpy(), add the new data, then deallocate the original memory. You can use:

delete ptr[];

to do that. Some compilers require you to have the size in the subset brackets though.