2.10.3 Array Declarations and Storage

In addition to the dynamic associative arrays that are described in Section 2.9, “Variables”, D supports scalar arrays. Scalar arrays are a fixed-length group of consecutive memory locations that each store a value of the same type. Scalar arrays are accessed by referring to each location with an integer, starting from zero. Scalar arrays correspond directly in concept and syntax with arrays in C and C++. Scalar arrays are not used as frequently in D as associative arrays and their more advanced counterparts aggregations. You might, however, need to use scalar arrays to access existing operating system array data structures that are declared in C. Aggregations are described in Chapter 3, Aggregations.

A D scalar array of 5 integers is declared by using the type int and suffixing the declaration with the number of elements in square brackets, for example:

int a[5];

Figure 2.3, “Scalar Array Representation” shows a visual representation of the array storage:

Figure 2.3 Scalar Array Representation

The figure illustrates the elements a[0] through a[4] of the array, declared as a[5], arranged side-by-side in memory.

The D expression a[0] refers to the first array element, a[1] refers to the second, and so on. From a syntactic perspective, scalar arrays and associative arrays are very similar. You can declare an associative array of integers referenced by an integer key as follows:

int a[int];

You can also reference this array using the expression a[0]. But, from a storage and implementation perspective, the two arrays are very different. The static array a consists of five consecutive memory locations numbered from zero, and the index refers to an offset in the storage that is allocated for the array. On the other hand, an associative array has no predefined size and does not store elements in consecutive memory locations. In addition, associative array keys have no relationship to the corresponding value storage location. You can access associative array elements a[0] and a[-5] and only two words of storage are allocated by DTrace, and these might or might not be consecutive. Associative array keys are abstract names for the corresponding values and have no relationship to the value storage locations.

If you create an array using an initial assignment and use a single integer expression as the array index , for example, a[0] = 2, the D compiler always creates a new associative array, even though in this expression a could also be interpreted as an assignment to a scalar array. Scalar arrays must be predeclared in this situation so that the D compiler can recognize the definition of the array size and infer that the array is a scalar array.