Question about arrays

Ali Çehreli acehreli at yahoo.com
Sun Apr 22 18:52:00 PDT 2012


On 04/22/2012 03:17 PM, Stephen Jones wrote:
 > Thanks for the replies. I am still uncertain about something. The
 > documentation distinguishes between dynamic slices (int[5] a = new
 > int[5])

The documentation may be incorrect because int[5] is never a slice. It 
is a fixed-length array.

As an aside, I don't like calling fixed-length arrays static arrays, 
because static implies compile time. Fine, the length is known at 
compile time but as your code above demonstrates, the storage can be 
allocated at runtime, dynamically.

 > which are managed by the runtime, and stack allocated arrays
 > (int[5] b).

"Stack allocated" may also be misleading because a fixed-length array 
can be a part of a type that is allocated dynamically:

class Foo
{
     int[5] b;  // <-- not on the stack
}

As jerro explained, a slice is a pointer to the first element and a 
length. A fixed-length array is N elements side by side.

 > My confusion is, if the syntax for both stack based and managed memory
 > arrays is the same (&v[0] or &v.ptr)

You must have meant &v[0] and v.ptr. It is the same for both types:

     // fixed-length
     {
         int[5] a = new int[5];
         auto firstElem_1 = a.ptr;
         auto firstElem_2 = &a[0];
         assert(firstElem_1 == firstElem_2);
     }

     // slice
     {
         int[] a = new int[5];
         auto firstElem_1 = a.ptr;
         auto firstElem_2 = &a[0];
         assert(firstElem_1 == firstElem_2);
     }

Ali



More information about the Digitalmars-d-learn mailing list