Pointers in D Programming Language

D supports pointers, allowing you to pass references to values and records within your program.

import std.stdio;

// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
void zeroval(int ival) {
    ival = 0;
}

// `zeroptr` in contrast has an `int*` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then *dereferences* the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
void zeroptr(int* iptr) {
    *iptr = 0;
}

void main() {
    int i = 1;
    writeln("initial:", i);

    zeroval(i);
    writeln("zeroval:", i);

    // The &i syntax gives the memory address of `i`,
    // i.e. a pointer to `i`.
    zeroptr(&i);
    writeln("zeroptr:", i);

    // Pointers can be printed too.
    writeln("pointer:", &i);
}

zeroval doesn’t change the i in main, but zeroptr does because it has a reference to the memory address for that variable.

$ dmd -run pointers.d
initial:1
zeroval:1
zeroptr:0
pointer:7FFF5A5E7B28

In this D version:

  1. We use import std.stdio; to import the standard input/output module.
  2. The zeroval and zeroptr functions are defined similarly to the original, with int* used for the pointer type.
  3. In the main function, we use writeln instead of fmt.Println for output.
  4. The syntax for getting a pointer (&i) and dereferencing a pointer (*iptr) is the same as in the original.
  5. To compile and run a D program, we use the D compiler dmd with the -run flag, which compiles and executes the program in one step.

The behavior of the program remains the same, demonstrating how pointers work in D compared to passing values.