In this chapter, you will learn about how to use pointers and static arrays in D. You will also learn how to pass by reference without using pointers. The lesson text will not explain the concepts behind pointers and arrays, and it will assume that you have that knowledge from C or C++. D also has dynamic arrays and array slices, both of which will be covered in a later lesson.

If you're a C++ programmer and you read the above thinking it's a step back from C++ references, then rejoice: while D supports pointers, it also supports better solutions for passing variables by reference to functions:

importstd.stdio;voidadd_numbers(refinta,intb){a+=b;}voidmain(){intc=2;intd=2;add_numbers(c,d);writeln(c);// 4// add_numbers(4, 2); Error: integer literals are not lvalues and cannot be passed by reference}

Arrays are indexed starting with the number zero for the first element. The compiler will catch you if you attempt to access an element with an index greater than or equal to that array's length. You access elements of an array like this:

my_array[index]

You can also fill an array with a single value, so that all of that array's elements equal that value:

The output is [1,2,3], not [2,2,3]. Why? It's because static arrays are copied whenever they are passed as arguments to a function. The arr in the addOne function is only a copy of array1. Rewrite it like this: