Title here
Summary here
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:
import std.stdio;
to import the standard input/output module.zeroval
and zeroptr
functions are defined similarly to the original, with int*
used for the pointer type.main
function, we use writeln
instead of fmt.Println
for output.&i
) and dereferencing a pointer (*iptr
) is the same as in the original.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.