Address of an array

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 27 09:29:03 PDT 2016


On Thursday, October 27, 2016 16:13:34 David via Digitalmars-d-learn wrote:
> Hi
>
> The pointer (.ptr) of an array is the address of the first array
> element. But what exactly is the address of the array? And how is
> it used?
>
>    auto myArray = [5, 10, 15, 20, 25, 30, 35];
>    writeln("myArray.ptr: ", myArray.ptr); // myArray.ptr:
> 7FFA95F29000
>    writeln("&myArray[0]: ", &myArray[0]); // &myArray[0]:
> 7FFA95F29000
>    writeln("&myArray: ", &myArray); // &myArray: 7FFE4B576B10
>    writeln("*&myArray: ", *&myArray); // *&myArray: [5, 10, 15,
> 20, 25, 30, 35]

A dynamic array looks something kind of like this:

struct DynamicArray(T)
{
    size_t length;
    T* ptr;
}

So, if you take the address of a dynamic array, you're basically taking the
address of a struct on the stack, whereas the address in ptr is the address
in memory where the data is (be it GC-allocated memory, malloc-ed memory, or
a static array on the stack somewhere).

Similarly, if you have a class reference, and you take its address, you're
taking the address of the reference, not the class object that it points to.
e.g.

class MyClass
{
    string foo;
}

MyClass mc;
auto addr = &mc;

addr is the address of mc on the stack, whereas mc itself is null.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list