On 14 Oct, 07:56, Steve555 <foursh...@btinternet.com> wrote:
> On 14 Oct, 07:46, Project China Blue Book <chine.b...@yahoo.com>
> wrote:
>
>
>
>
>
> > In article <8bc0d55d-db30-45c7-83fd-880fb82f5...@a36g2000yqc.googlegroups.com>,
>
> > *Steve555 <foursh...@btinternet.com> wrote:
> > > I've been working with C++ and Objective-C and I've forgotten how to
> > > allocate memory for an array of structs in C.
> > > MyStruct * **myStructArray;
> > > myStructArray = new MyStruct*[1024];
>
> > This is an array of struct pointers, not an array of structs.
>
> > > for(long i=0; i<1024; i++){
> > > * * myStructArray[i] = new MyStruct;
> > > }
> > > so that I can access them by index:
>
> > > double a = myStructArray[1]->a;
>
> > myStructArray = malloc(1024*sizeof(MyStruct));
> > ...
> > * * myStructArray[i] = malloc(sizeof(MyStruct));
>
> > > I'm aware of malloc as a simple lump of memory, but don't understand
> > > how it would be aware of the boundaries of each struct and each
> > > element.
>
> > It doesn't need to be aware. You allocate a separate block for each struct as a
> > pointer, and one block for the array of pointers. The address arithmetic picks
> > the correct pointer out of the array, assuming you don't lie about the array
> > size, and the pointer deref gets the struct value.
>
> > If you want to allocate an array of structs, that's just
> > * * MyStruct **myStructArray = malloc(1024*sizeof(MyStruct));
> > * * ...
> > * * double a = myStructArray[1].a;
>
> > --
> > Damn the living - It's a lovely life. * * * * * I'm whoever you want me to be.
> > Silver silverware - Where is the love? * * * At least I can stay in character.
> > Oval swimming pool - Where is the love? * *Annoying Usenet one post at a time.
> > Damn the living - It's a lovely life. * * May your creator bless and keep you.
>
> double a = myStructArray[1].a;
>
> Thanks, but in case I didn't explain well enough, the crucial point is
> that I need pointers:
>
> double a = myStructArray[1]->a;
>
> I'm passing large structures by pointer to time-critical functions to
> save the overhead of copying.
MyStruct **myStructArray;
myStructArray = (MyStruct*)malloc(1024 * sizeof(MyStruct*))
for(long i=0; i<1024; i++){
myStructArray[i] = malloc(sizeof(MyStruct));
myStructArray[i]->g = i;
}
printf("%d", myStructArray[123]->g);
OK, well that *seems* to work, but as with all memory problems, I
might just have got lucky.
If any kind soul spots a lurking catastrophe, I'd appreciate a heads-
up