how can I get a reference of array?

FG via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 5 05:30:32 PST 2015


On 2015-02-05 at 09:58, bearophile wrote:
> zhmt:
>
>> Will arr.ptr change in the future?
>>
>> As the array add more members , it need more memroy, then remalloc may be called, the pointer maybe change, then the stored pointer will be invalid.
>>
>> Will this happen?
>
> Yes, it can happen.

Therefore, don't use arr.ptr directly, but always access it via arr or a.arr.

     class A { public int[] * arr; }
     int[] arr;
     A a = new A;
     a.arr = &arr;
     ... // lots of adding to arr
     ... // and yet still, a.arr == &arr

Even when the array in the memory gets reallocated by adding to arr, causing arr.length and arr.ptr to be updated, the arr struct itself will remain in the same spot, so pointers to it, including a.arr, are valid. (Unless arr goes out of scope before a, in which case you would be in deep trouble.)


More information about the Digitalmars-d-learn mailing list