Get object address when creating it in for loop

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon May 5 10:25:02 PDT 2014


On Mon, 05 May 2014 16:15:42 +0000
hardcoremore via Digitalmars-d <digitalmars-d at puremagic.com> wrote:

> How to get and address of newly created object and put it in
> pointer array?
>
>
> int maxNeurons = 100;
> Neuron*[] neurons = new Neuron*[](maxNeurons);
>
> Neuron n;
>
> for(int i = 0; i < maxNeurons; i++)
> {
>          n = new Neuron();
>   neurons[] = &n; // here &n always returns same adress
> }
>
> writefln("Thread func complete. Len: %s", neurons);
>
>
> This script above will print array with all the same address
> values, why is that?

&n gives you the address of the local variable n, not of the object on the
heap that it points to. You don't normally get at the address of class objects
in D. There's rarely any reason to. Classes always live on the heap, so
they're already references. Neuron* is by definition a pointer to a class
_reference_ not to an instance of Neuron. So, you'd normally do

Neuron[] neurons;

for your array. I very much doubt that you really want an array of Neuron*.
IIRC, you _can_ get at an address of a class instance by casting its reference
to void*, but I'm not sure, because I've never done it. And even then, you're
then using void*, not Neuron*.

Also FYI, questions like this belong in D.learn. The D newsgroup is for
general discussions about D, not for questions related to learning D.

- Jonathan M Davis


More information about the Digitalmars-d mailing list