How to allocate arrays of objects?
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Feb 10 20:29:43 PST 2016
On Thursday, 11 February 2016 at 04:07:18 UTC, cy wrote:
> The following program segfaults for me, compiling it with
> dmdv2.070 as well as the latest git. I must be doing it wrong.
> There's a way to specify class construction, or emplace, or
> something. But I can't find it! How do I deal with arrays of
> objects?
>
> class A {
> int stuff;
> }
>
> void main()
> {
> A[] as = new A[2];
> assert(as.length==2);
> as[0].stuff = 42;
> }
>
> Looking at it in gdb, the program segfaults on "A[] as = new
> A[2]" and never reaches "as[0].stuff = 42". But removing
> "as[0].stuff = 42" causes the program to stop segfaulting!
> assert(as.length == 2) doesn't get reached either.
You've allocated space for two class references, but you haven't
actually allocated any class instances. This means both as[0] and
as[1] are null, hence your segfault.
More information about the Digitalmars-d-learn
mailing list