Get object address when creating it in for loop

Nick Sabalausky via Digitalmars-d digitalmars-d at puremagic.com
Mon May 5 09:21:48 PDT 2014


On 5/5/2014 12:15 PM, hardcoremore 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?
>
>
> Thanks

These sorts of questions should go in digitalmars.D.learn, but your 
problem is a simple typo here:

neurons[] = &n;

That sets the *entire* array to "&n". You forgot the index:

neurons[i] = &n;




More information about the Digitalmars-d mailing list