...

/

Use of Pointers with Arrays

Use of Pointers with Arrays

Learn how pointers can be used with arrays.

Pointers are risky

The compiler and the D runtime environment cannot guarantee that the pointers are always used correctly. It is the programmer’s responsibility to ensure that a pointer is either null or points at a valid memory location (at a variable, an element of an array, etc.).

Therefore, it is always better to consider higher-level features of D before thinking about using pointers.

The element one past the end of an array

It is valid to point at the imaginary element one past the end of an array.

This is a useful idiom similar to number ranges. When defining a slice with a number range, the second index is one past the elements of the slice:

Press + to interact
import std.stdio;
void main() {
int[] values = [ 0, 1, 2, 3 ];
writeln(values[1 .. 3]); // 1 and 2 included, 3 excluded
}

This idiom can also be used with pointers. It is a common function design in C and C++ where a function parameter points at the first element and another one points at the element after the last ...