Creating an array of user-defined structs
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 21 16:37:38 PDT 2016
On Sunday, 21 August 2016 at 23:28:14 UTC, brian wrote:
> /* creates(?) an empty array of structs */
> testStruct[int] testStructArray;
That's not actually an array per se, that is a key/value map
where the keys are ints.
So you can set values to it at any position in it but not append
or do other traditional array operations.
An ordinary array is defined with
testStruct[] testStructArray;
though what you have isn't necessarily wrong.
> auto newStruct = new testStruct;
This is the cause of the pointer mismatch error - new struct
returns a pointer to it. If you just want an ordinary struct you
define it:
testStruct newStruct;
like that.
> newStruct.aa = a.dup;
> newStruct.bb = b.dup;
No need for the .dup there because strings aren't going to be
changing under you anyway.
> 1) I'm assuming by the error that line 23 defines a pointer
> rather than a ... not-pointer thing. I'm not sure why it is
> doing that, and would like some explanation please. :)
It is just how new works in D, it returns a reference. For
structs, that means a pointer to it.
> 2) Is this the best way to do what I am trying to do, which is
> dynamically grow an array of user defined structs?
Either do a traditional array and copy struct values onto it or
do an array of pointers and new them. Which option is bsed
depends on the details of what you're doing.
More information about the Digitalmars-d-learn
mailing list