|
|||
2. Types, Operators, and Expressions Pointer and Array Relationship 8. Type and Constant Definitions 34. Statically Defined Tracing for User Applications |
Array Declarations and StorageD provides support for scalar arrays in addition to the dynamic associative arrays described in Chapter 3. 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, but these are sometimes needed when accessing existing operating system array data structures declared in C. Aggregations are described in Chapter 9, Aggregations. A D scalar array of 5 integers would be declared by using the type int and suffixing the declaration with the number of elements in square brackets as follows: int a[5]; The following diagram shows a visual representation of the array storage: Figure 5-1 Scalar Array RepresentationThe D expression a[0] is used to refer 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 five integers referenced by an integer key as follows: int a[int]; and 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 allocated for the array. An associative array, on the other hand, has no predefined size and does not store elements in consecutive memory locations. In addition, associative array keys have no relationship to the corresponding's value storage location. You can access associative array elements a[0] and a[-5] and only two words of storage will be allocated by DTrace which may or may not be consecutive. Associative array keys are abstract names for the corresponding value that 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 will always create 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 see the definition of the array size and infer that the array is a scalar array. |
||
|