Arrays

There are four kinds of arrays:

int * p;

These are simple pointers to data, analogous to C pointers. Pointers are provided for interfacing with C and for specialized systems work. There is no length associated with it, and so there is no way for the compiler or runtime to do bounds checking, etc., on it. Most conventional uses for pointers can be replaced with dynamic arrays, out and ref parameters, and reference types.

int [3] s;

These are analogous to C arrays. Static arrays are distinguished by having a length fixed at compile time.

The total size of a static array cannot exceed 16Mb. A dynamic array should be used instead for such large arrays.

A static array with a dimension of 0 is allowed, but no space is allocated for it. It's useful as the last member of a variable length struct, or as the degenerate case of a template expansion.

Static arrays are value types. Unlike in C and D version 1, static arrays are passed to functions by value. Static arrays can also be returned by functions.

int [] a;

Dynamic arrays consist of a length and a pointer to the array data. Multiple dynamic arrays can share all or parts of the array data.

Array Declarations

There are two ways to declare arrays, prefix and postfix. The prefix form is the preferred method, especially for non-trivial types.

Prefix Array Declarations

Prefix declarations appear before the identifier being declared and read right to left, so:

int [] a; int [4][3] b; int [][5] c; int *[]*[3] d; int []* e;

Postfix Array Declarations

Postfix declarations appear after the identifier being declared and read left to right. Each group lists equivalent declarations:

int [] a; int a[]; int [4][3] b; int [4] b[3]; int b[3][4]; int [][5] c; int [] c[5]; int c[5][]; int *[]*[3] d; int *[]* d[3]; int * (*d[3])[]; int []* e; int (*e)[];

Rationale: The postfix form matches the way arrays are declared in C and C++, and supporting this form provides an easy migration path for programmers used to it.

There are two broad kinds of operations to do on an array - affecting the handle to the array, and affecting the contents of the array. C only has operators to affect the handle. In D, both are accessible.

The handle to an array is specified by naming the array, as in p, s or a:

int * p; int [3] s; int [] a; int * q; int [3] t; int [] b; p = q; p = s.ptr; p = a.ptr; s = ...; a = p; a = s; a = b;

Slicing an array means to specify a subarray of it. An array slice does not copy the data, it is only another reference to it. For example:

int [10] a; int [] b; b = a[1..3]; foo(b[1]); a[2] = 3; foo(b[1]);

The [] is shorthand for a slice of the entire array. For example, the assignments to b:

int [10] a; int [] b; b = a; b = a[]; b = a[0 .. a.length];

are all semantically equivalent.

Slicing is not only handy for referring to parts of other arrays, but for converting pointers into bounds-checked arrays:

int * p; int [] b = p[0..8];

When the slice operator appears as the lvalue of an assignment expression, it means that the contents of the array are the target of the assignment rather than a reference to the array. Array copying happens when the lvalue is a slice, and the rvalue is an array of or pointer to the same type.

int [3] s; int [3] t; s[] = t; s[] = t[]; s[1..2] = t[0..1]; s[0..2] = t[1..3]; s[0..4] = t[0..4]; s[0..2] = t;

Overlapping copies are an error:

s[0..2] = s[1..3]; s[1..3] = s[0..2];

Disallowing overlapping makes it possible for more aggressive parallel code optimizations than possible with the serial semantics of C.

If a slice operator appears as the lvalue of an assignment expression, and the type of the rvalue is the same as the element type of the lvalue, then the lvalue's array contents are set to the rvalue.

int [3] s; int * p; s[] = 3; p[0..2] = 3;

The binary operator ~ is the cat operator. It is used to concatenate arrays:

int [] a; int [] b; int [] c; a = b ~ c;

Many languages overload the + operator to mean concatenation. This confusingly leads to, does:

"10" + 3 + 4

produce the number 17, the string "1034" or the string "107" as the result? It isn't obvious, and the language designers wind up carefully writing rules to disambiguate it - rules that get incorrectly implemented, overlooked, forgotten, and ignored. It's much better to have + mean addition, and a separate operator to be array concatenation.

Similarly, the ~= operator means append, as in:

a ~= b;

Concatenation always creates a copy of its operands, even if one of the operands is a 0 length array, so:

a = b; a = b ~ c[0..0];

Appending does not always create a copy, see setting dynamic array length for details.

Many array operations, also known as vector operations, can be expressed at a high level rather than as a loop. For example, the loop:

T[] a, b; ... for (size_t i = 0; i < a.length; i++) a[i] = b[i] + 4;

assigns to the elements of a the elements of b with 4 added to each. This can also be expressed in vector notation as:

T[] a, b; ... a[] = b[] + 4;

A vector operation is indicated by the slice operator appearing as the lvalue of an =, +=, -=, *=, /=, %=, ^=, &= or |= operator. The rvalue can be an expression consisting either of an array slice of the same length and type as the lvalue or an expression of the element type of the lvalue, in any combination. The operators supported for vector operations are the binary operators +, -, *, /, %, ^, & and |, and the unary operators - and ~.

The lvalue slice and any rvalue slices must not overlap. The vector assignment operators are evaluated right to left, and the other binary operators are evaluated left to right. All operands are evaluated exactly once, even if the array slice has zero elements in it.

The order in which the array elements are computed is implementation defined, and may even occur in parallel. An application must not depend on this order.

Implementation note: many of the more common vector operations are expected to take advantage of any vector math instructions available on the target computer.

int [3] abc; int [] def = [ 1, 2, 3 ]; void dibb( int * array) { array[2]; *(array + 2); } void diss( int [] array) { array[2]; *(array + 2); } void ditt( int [3] array) { array[2]; *(array + 2); }

Experienced FORTRAN numerics programmers know that multidimensional "rectangular" arrays for things like matrix operations are much faster than trying to access them via pointers to pointers resulting from "array of pointers to array" semantics. For example, the D syntax:

double [][] matrix;

declares matrix as an array of pointers to arrays. (Dynamic arrays are implemented as pointers to the array data.) Since the arrays can have varying sizes (being dynamically sized), this is sometimes called "jagged" arrays. Even worse for optimizing the code, the array rows can sometimes point to each other! Fortunately, D static arrays, while using the same syntax, are implemented as a fixed rectangular layout:

double [3][3] matrix;

declares a rectangular matrix with 3 rows and 3 columns, all contiguously in memory. In other languages, this would be called a multidimensional array and be declared as:

double matrix[3,3];

Within the [ ] of a static or a dynamic array, the symbol $ represents the length of the array.

int [4] foo; int [] bar = foo; int * p = &foo[0]; bar[] bar[0 .. 4] bar[0 .. $] bar[0 .. bar.length] p[0 .. $ ] bar[0]+$ bar[$ -1]

Static array properties are:

Static Array Properties Property Description .init Returns an array literal with each element of the literal being the .init property of the array element type. .sizeof Returns the array length multiplied by the number of bytes per array element. .length Returns the number of elements in the array. This is a fixed quantity for static arrays. It is of type size_t. .ptr Returns a pointer to the first element of the array. .dup Create a dynamic array of the same size and copy the contents of the array into it. .idup Create a dynamic array of the same size and copy the contents of the array into it. The copy is typed as being immutable. D 2.0 only .reverse Reverses in place the order of the elements in the array. Returns the array. .sort Sorts in place the order of the elements in the array. Returns the array.

Dynamic array properties are:

Dynamic Array Properties Property Description .init Returns null. .sizeof Returns the size of the dynamic array reference, which is 8 in 32-bit builds and 16 on 64-bit builds. .length Get/set number of elements in the array. It is of type size_t. .ptr Returns a pointer to the first element of the array. .dup Create a dynamic array of the same size and copy the contents of the array into it. .idup Create a dynamic array of the same size and copy the contents of the array into it. The copy is typed as being immutable. D 2.0 only .reverse Reverses in place the order of the elements in the array. Returns the array. .sort Sorts in place the order of the elements in the array. Returns the array.

For the .sort property to work on arrays of class objects, the class definition must define the function: int opCmp(Object) . This is used to determine the ordering of the class objects. Note that the parameter is of type Object , not the type of the class.

For the .sort property to work on arrays of structs or unions, the struct or union definition must define the function: int opCmp(ref const S) const . The type S is the type of the struct or union. This function will determine the sort ordering.

Examples:

int * p; int [3] s; int [] a; p.length; s.length; a.length; p.dup; s.dup; a.dup;

The .length property of a dynamic array can be set as the lvalue of an = operator:

array.length = 7;

This causes the array to be reallocated in place, and the existing contents copied over to the new array. If the new array length is shorter, the array is not reallocated, and no data is copied. It is equivalent to slicing the array:

array = array[0..7];

If the new array length is longer, the remainder is filled out with the default initializer.

To maximize efficiency, the runtime always tries to resize the array in place to avoid extra copying. It will always do a copy if the new size is larger and the array was not allocated via the new operator or resizing in place would overwrite valid data in the array.

char [] a = new char [20]; char [] b = a[0..10]; char [] c = a[10..20]; char [] d = a; b.length = 15; b[11] = 'x'; d.length = 1; d.length = 20; c.length = 12; c[5] = 'y'; a.length = 25; a[15] = 'z';

For example:

To guarantee copying behavior, use the .dup property to ensure a unique array that can be resized. Also, one may use the phobos .capacity property to determine how many elements can be appended to the array without reallocating.

These issues also apply to appending arrays with the ~= operator. Concatenation using the ~ operator is not affected since it always reallocates.

Resizing a dynamic array is a relatively expensive operation. So, while the following method of filling an array:

int [] array; while (1) { c = getinput(); if (!c) break ; ++array.length; array[array.length - 1] = c; }

will work, it will be inefficient. A more practical approach would be to minimize the number of resizes:

int [] array; array.length = 100; for (i = 0; ; i++) { c = getinput(); if (!c) break ; if (i == array.length) array.length *= 2; array[i] = c; } array.length = i;

Picking a good initial guess is an art, but you usually can pick a value covering 99% of the cases. For example, when gathering user input from the console - it's unlikely to be longer than 80.

Also, you may wish to utilize the phobos reserve function to pre-allocate array data to use with the append operator.

If the first parameter to a function is an array, the function can be called as if it were a property of the array:

int [] array; void foo( int [] a, int x); foo(array, 3); array.foo(3);

It is an error to index an array with an index that is less than 0 or greater than or equal to the array length. If an index is out of bounds, a RangeError exception is raised if detected at runtime, and an error if detected at compile time. A program may not rely on array bounds checking happening, for example, the following program is incorrect:

try { for (i = 0; ; i++) { array[i] = 5; } } catch (RangeError) { }

for (i = 0; i < array.length; i++) { array[i] = 5; }

The loop is correctly written:

Implementation Note: Compilers should attempt to detect array bounds errors at compile time, for example:

int [3] foo; int x = foo[3];

Insertion of array bounds checking code at runtime should be turned on and off with a compile time switch.

Pointers are initialized to null .

. Static array contents are initialized to the default initializer for the array element type.

Dynamic arrays are initialized to having 0 elements.

Associative arrays are initialized to having 0 elements.

Void initialization happens when the Initializer for an array is void. What it means is that no initialization is done, i.e. the contents of the array will be undefined. This is most useful as an efficiency optimization. Void initializations are an advanced technique and should only be used when profiling indicates that it matters.

Static initalizations are supplied by a list of array element values enclosed in [ ]. The values can be optionally preceded by an index and a :. If an index is not supplied, it is set to the previous index plus 1, or 0 if it is the first value.

int [3] a = [ 1:2, 3 ];

This is most handy when the array indices are given by enums:

enum Color { red, blue, green }; int value[Color.max + 1] = [ Color.blue :6, Color.green:2, Color.red :5 ];

These arrays are statically allocated when they appear in global scope. Otherwise, they need to be marked with const or static storage classes to make them statically allocated arrays.

A string is an array of characters. String literals are just an easy way to write character arrays. String literals are immutable (read only).

char [] str1 = "abc" ; char [] str2 = "abc" .dup; immutable ( char )[] str3 = "abc" ; immutable ( char )[] str4 = str1; immutable ( char )[] str5 = str1.idup;

The name string is aliased to immutable(char)[] , so the above declarations could be equivalently written as:

char [] str1 = "abc" ; char [] str2 = "abc" .dup; string str3 = "abc" ; string str4 = str1; string str5 = str1.idup;

char[] strings are in UTF-8 format. wchar[] strings are in UTF-16 format. dchar[] strings are in UTF-32 format.

Strings can be copied, compared, concatenated, and appended:

str1 = str2; if (str1 < str3) ... func(str3 ~ str4); str4 ~= str1;

with the obvious semantics. Any generated temporaries get cleaned up by the garbage collector (or by using alloca() ). Not only that, this works with any array not just a special String array.

A pointer to a char can be generated:

char * p = &str[3]; char * p = str;

Since strings, however, are not 0 terminated in D, when transferring a pointer to a string to C, add a terminating 0:

str ~= "\0" ;

or use the function std.string.toStringz .

The type of a string is determined by the semantic phase of compilation. The type is one of: char[], wchar[], dchar[], and is determined by implicit conversion rules. If there are two equally applicable implicit conversions, the result is an error. To disambiguate these cases, a cast or a postfix of c, w or d can be used:

cast ( immutable ( wchar ) []) "abc" "abc"w

String literals that do not have a postfix character and that have not been cast can be implicitly converted between string, wstring, and dstring as necessary.

char c; wchar w; dchar d; c = 'b'; w = 'b'; w = 'bc'; w = "b" [0]; w = "\r" [0]; d = 'd';

printf() is a C function and is not part of D. printf() will print C strings, which are 0 terminated. There are two ways to use printf() with D strings. The first is to add a terminating 0, and cast the result to a char*:

str ~= "\0" ; printf( "the string is '%s'

" , cast ( char *)str);

or:

import std.string; printf( "the string is '%s'

" , std.string.toStringz(str));

String literals already have a 0 appended to them, so can be used directly:

printf( "the string is '%s'

" , cast ( char *) "string literal" );

So, why does the first string literal to printf not need the cast? The first parameter is prototyped as a const(char)*, and a string literal can be implicitly cast to a const(char)*. The rest of the arguments to printf, however, are variadic (specified by ...), and a string literal is passed as a (length,pointer) combination to variadic parameters.

The second way is to use the precision specifier. The length comes first, followed by the pointer:

printf( "the string is '%.*s'

" , str.length, str.ptr);

The best way is to use std.stdio.writefln, which can handle D strings:

import std.stdio; writefln( "the string is '%s'" , str);

A pointer T* can be implicitly converted to one of the following:

void*

A static array T[dim] can be implicitly converted to one of the following:

T []

const( U )[]

void[]

A dynamic array T[] can be implicitly converted to one of the following:

const( U )[]

void[]

Where U is a base class of T.