static array of pointers to dynamic arrays of ints problem...

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 23 13:55:44 UTC 2018


On 4/22/18 2:00 AM, WhatMeForget wrote:
> Surely a stupid mistake on my part, but why is the first array repeated?

In addition to what Neia said, you shouldn't use pointers to dynamic 
arrays. Such things are really hard to allocate on the heap, since new 
int[] just makes an array, not a pointer to an array. You're way more 
likely to accidentally store pointers to stack variables (as demonstrated).

The only way 2 ways I know of to do it are to a) allocate a 
multi-dimensional array, and take it's pointer (e.g. (new int[][1]).ptr) 
or b) create a dummy struct with an array in it, and new that:

Struct Dummy { int[] array; }

auto p = new Dummy;
auto ptr = &p.array;

Just use int[][2] a, you will be better off.

-Steve


More information about the Digitalmars-d-learn mailing list