Chuyển đến nội dung

Bài 15 · Arrays and Ranges

Arrays in D: Static and Dynamic Arrays

Learn D's two array kinds: fixed-size static arrays and growable dynamic arrays, with length, append, concatenation, array-wise operations, multidimensional arrays and bounds checking.

Arrays are the workhorse data structure, and D gets them right where C stumbles: an array knows its length, indexing is bounds-checked, and growing an array takes one operator. D has two kinds. A static array has a size fixed at compile time and lives wherever you declare it. A dynamic array can grow and is described by a pointer and a length. This lesson covers both, plus array operations, multidimensional arrays and common pitfalls. D code is read-only; the C stand-ins model the layout.

Static arrays

The size goes in the brackets after the element type:

D
import std.stdio;

void main()
{
    int[5] a = [10, 20, 30, 40, 50];
    int[3] zeros;                  // default-initialized: 0, 0, 0
    int[4] sevens = 7;             // every element is 7
    writeln(a.length);             // 5
    writeln(a[2]);                 // 30
    writeln(zeros);                // [0, 0, 0]
    writeln(sevens);               // [7, 7, 7, 7]
}

A static array is a value type: assigning it copies every element, and passing it to a function copies it too.

D
int[3] x = [1, 2, 3];
int[3] y = x;       // copy
y[0] = 99;
writeln(x[0]);      // 1 (x is unchanged)

Dynamic arrays

A dynamic array is declared without a size:

D
int[] list = [3, 1, 4];
list ~= 1;                       // append one element
list ~= [5, 9];                  // append several
auto more = list ~ [2, 6];       // concatenation makes a new array
writeln(list);                   // [3, 1, 4, 1, 5, 9]
writeln(list.length);            // 6
list.length = 3;                 // shrink (the data beyond is not erased in memory)
writeln(list);                   // [3, 1, 4]

~= appends, growing the underlying memory as needed, and the runtime reserves extra capacity so repeated appends are cheap. If you know the size, list.reserve(1000) avoids repeated growth, and new int[](n) allocates n zero-initialized elements. Useful library helpers: std.array.array, std.algorithm.sort, std.range.iota.

Bounds checking

Reading or writing outside an array throws a RangeError (an Error) in normal builds:

D
int[] a = [1, 2, 3];
// writeln(a[3]);       // core.exception.RangeError: Range violation

This is a major safety win compared with C, where the same mistake silently reads another variable's memory. -release still checks arrays in @safe code. Use a.length and foreach to avoid indexing errors, and a[$ - 1] for the last element ($ stands for the length inside an index).

Array-wise operations

Operations apply to whole arrays at once, without a loop:

D
int[] a = [1, 2, 3];
int[] b = [10, 20, 30];
int[] c = new int[3];

c[] = a[] + b[];        // [11, 22, 33]
a[] *= 2;               // [2, 4, 6]
b[] = 0;                // [0, 0, 0]

The lengths must match, and the compiler can vectorize the loop. Comparison a == b compares contents element by element.

Multidimensional arrays

D
int[3][2] grid;                   // 2 rows of 3: note the reversed order of the sizes
grid[1][2] = 7;
writeln(grid);                    // [[0, 0, 0], [0, 0, 7]]

int[][] table = [[1, 2], [3, 4, 5], [6]];   // jagged: rows of different length
writeln(table[1].length);         // 3

In int[3][2], the type reads from the right: two elements, each an int[3]. A dynamic int[][] is an array of slices, so rows may have different sizes and must each be allocated.

Sorting, searching and printing

D
import std.algorithm : sort, canFind, maxElement;
import std.stdio;

void main()
{
    int[] data = [42, 7, 19, 3];
    data.sort();                       // in place
    writeln(data);                     // [3, 7, 19, 42]
    writeln(data.canFind(19));         // true
    writeln(data.maxElement);          // 42
}

C stand-ins: arrays that carry their length

A D array is a pointer and a length. C can model that with a struct, adding the bounds check D does automatically.

C C stand-in: a dynamic array with append and bounds check

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program prints 3 1 4 1 5, then length 5, capacity 8, then last = 5, and finally the RangeError message before exiting. D's runtime does the growth and the check without any of this code.

C C stand-in: static arrays are copied by value when wrapped in a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You will see x[0] = 1, y[0] = 99 and 11 22 33. In plain C a bare array would decay to a pointer on assignment; D's static arrays keep value semantics.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What happens when you assign one static array to another?

    Static arrays are value types.
  2. 2. What does a[$ - 1] mean?

    $ is the array length inside an index, so $ - 1 is the last index.
  3. 3. What operator appends to a dynamic array?

    ~= appends an element or an array.
  4. 4. What does int[3][2] describe?

    Read from the right: two elements, each an int[3].

Summary

  • Static arrays (int[5]) have a fixed size and are value types; dynamic arrays (int[]) can grow with ~=.
  • Arrays know their length and are bounds-checked.
  • Array-wise operators (c[] = a[] + b[]) process whole arrays without a loop.
  • int[3][2] is two rows of three; int[][] allows jagged rows.

Next: Slices in depth

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.