On Tue, 28 Feb 2012 03:30:01 -0500, Mikael Lindsten <mik...@lindsten.net> wrote:

2012/2/28 Pedro Lacerda <pslace...@gmail.com>

So are a newly allocated array and a null one just the same thing?

    int[] a = [], b = null;
    assert(a == b);
    assert(a.length == b.length);
    assert(a.ptr == a.ptr);


Hi all,

Sorry if this is a stupid question - I'm new to D but I've been keeping an
eye on it for quite a while (and also read the book).

Coming from the Java/C# world, not distinguishing between an empty array
and null feels strange to me. Is this so for strings as well? ...and in
Pedros example, if you assign null to b and then try to access b.length,
don't you get a NullPointerException? What am I missing?

There is a major difference between Java/C# arrays and D arrays. The former are full-fledged objects, D is just a pointer + length.

In any case, a null array is an array which points at null and has 0 elements. Given it has no valid elements, it's a perfectly valid empty array. As demonstrated by this code:

int[] arr = null;
arr ~= 5; // append element works, even though arr originally pointed at null.

Do the same in C#/Java and you will get an exception.

D makes arrays as safe as possible, and as useful as possible. The pointer value itself is an implementation detail, and should rarely be used to determine logic.

-Steve

Reply via email to