Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Arrays and Ranges

Slices in Depth: Views, Aliasing and Appending in D

Understand that a D dynamic array is a slice (a pointer and a length), how slicing shares memory, when appending reallocates, and how to copy safely with dup and idup.

The most important idea in D's arrays is that int[] is not a container; it is a slice: a small struct holding a pointer to the first element and a length. The memory underneath is owned by the garbage collector (or a static array, or the stack). Many slices can look at overlapping parts of the same memory. Once you understand that, D's array behavior becomes predictable: slicing is free, copying a slice copies only two words, and appending sometimes moves your data. D listings are read-only; the C stand-in models a slice with a struct so you can see the aliasing.

A slice is a pointer and a length

flowchart LR
    S["slice: ptr, length 3"] --> M["memory: 10 20 30 40 50 60"]
    T["slice: ptr+2, length 2"] --> M

Two slices into one block of memory. Neither owns the data.

D
import std.stdio;

void main()
{
    int[] whole = [10, 20, 30, 40, 50, 60];
    int[] middle = whole[2 .. 5];      // elements 2, 3, 4
    writeln(middle);                   // [30, 40, 50]
    writeln(middle.length);            // 3

    middle[0] = 99;                    // changes the shared memory
    writeln(whole);                    // [10, 20, 99, 40, 50, 60]
}

a[start .. end] includes start and excludes end. No elements are copied: the slice middle points at whole's third element. Writing through one slice is visible through every slice that overlaps. Slicing is O(1), which makes recursive algorithms on subarrays (binary search, merge sort) cheap in D.

Taking the front off

Because a slice is just a window, you can shrink it by reassigning:

D
int[] a = [1, 2, 3, 4];
a = a[1 .. $];         // drop the first element; a is now [2, 3, 4]
a = a[0 .. $ - 1];     // drop the last; a is now [2, 3]

This is how D's ranges walk through arrays, with popFront implemented as exactly this assignment, covered in Ranges and algorithms.

Appending: when slices diverge

Appending with ~= writes into spare capacity if the slice reaches to the end of the block's used part. Otherwise, or when the block is full, the runtime allocates a new, larger block and copies the data. After a reallocation, the slice no longer shares memory with its siblings:

D
import std.stdio;

void main()
{
    int[] a = [1, 2, 3];
    int[] b = a;           // same memory
    b[0] = 100;
    writeln(a[0]);         // 100: shared

    b ~= 4;                // may reallocate
    b[1] = 200;
    writeln(a);            // depends on whether b was moved
}

What the last line prints depends on whether the original block had room to grow, and the language does not promise either outcome. If b ~= 4 reallocated, a stays [100, 2, 3]; if it grew in place, b[1] = 200 could be visible through a as well. The rule is simple: after you append, do not assume the old and new slices still share memory. If you need independence, copy explicitly.

Copying and the dup family

.dup makes a mutable copy of the elements, and .idup makes an immutable one:

D
int[] original = [1, 2, 3];
int[] copy = original.dup;      // new memory
copy[0] = 50;
writeln(original[0]);           // 1

string s = "abc";
char[] mutable = s.dup;         // string is immutable, so dup to edit
mutable[0] = 'X';
string back = mutable.idup;     // "Xbc"

To copy into existing memory, use a slice assignment with matching lengths: dest[] = source[]; (the slices must not overlap in a surprising way).

a.capacity reports how many elements the block can hold before reallocating, and a.reserve(n) raises it. assumeSafeAppend tells the runtime that no other slice looks at the data past this slice's end, allowing in-place reuse after shrinking.

Slices as function parameters

Passing a slice to a function copies only the pointer and length. The function sees the same elements, so writes to elements are visible to the caller, while changes to the slice itself (like appending) are not unless the parameter is ref. This makes functions such as void fill(int[] buffer, int value) allocation-free: you can hand them a window of a bigger buffer.

A C model of a slice

C C stand-in: slices that share memory

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 output is middle: 30 40 50, then whole : 10 20 99 40 50 60, then tail : 20 99 40 50 60. The write through middle changed whole, because no data was ever copied.

C C stand-in: dup copies, a slice does not

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 original: 100 2 3 (changed through the alias, not the copy) and copy: 1 200 3.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a D slice consist of?

    A slice is a view: pointer plus length.
  2. 2. What is the result of [10,20,30,40,50][1 .. 3]?

    The start is included and the end excluded: indexes 1 and 2.
  3. 3. Why should you not assume slices still share memory after ~=?

    When capacity runs out the runtime moves the data.
  4. 4. Which call gives you an independent mutable copy?

    dup allocates new memory and copies the elements.

Summary

  • A dynamic array is a slice: a pointer and a length over memory it does not own.
  • a[i .. j] is free and shares memory; writes through one slice show up in the others.
  • Appending may reallocate, breaking the sharing; use dup or idup for real copies.
  • Passing slices to functions is cheap, and element writes are visible to the caller.

Next: Associative arrays