Skip to content

Commit 7e666a8

Browse files
committed
[arrays.dd] Improve pointer docs
Document dereference and address of operators. Mention pointing to multiple elements and how this is not @safe.
1 parent cfb1643 commit 7e666a8

File tree

1 file changed

+40
-8
lines changed

1 file changed

+40
-8
lines changed

spec/arrays.dd

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,24 @@ $(H2 $(LNAME2 array-kinds, Kinds))
1818

1919
$(H3 $(LNAME2 pointers, Pointers))
2020

21+
$(P A pointer to type $(D T) has a value which is a reference (address) to another
22+
object of type $(D T). It is commonly called a $(I pointer to T) and it's type is
23+
`T*`. To access the object value, use the `*` dereference operator:
24+
)
25+
26+
$(SPEC_RUNNABLE_EXAMPLE_RUN
2127
---------
2228
int* p;
23-
---------
2429

25-
$(P A pointer to type $(I T) has a value which is a reference (address) to another
26-
object of type $(I T). It is commonly called a $(I pointer to T).
27-
)
30+
assert(p == null);
31+
p = new int(5);
32+
assert(p != null);
33+
34+
assert(*p == 5);
35+
(*p)++;
36+
assert(*p == 6);
37+
---------
38+
)
2839

2940
$(P If a pointer contains a $(I null) value, it is not pointing to a valid object.)
3041

@@ -43,12 +54,33 @@ int* p;
4354
to a valid object of type $(I T).)
4455
))
4556

46-
$(BEST_PRACTICE These are simple pointers to data.
47-
Pointers are provided for interfacing with C and for
57+
$(P To set a pointer to point at an existing object, use the
58+
`&` *address of* operator:
59+
60+
$(SPEC_RUNNABLE_EXAMPLE_RUN
61+
---------
62+
int i = 2;
63+
int* p = &i;
64+
65+
assert(p == &i);
66+
assert(*p == 2);
67+
*p = 4;
68+
assert(i == 4);
69+
---------
70+
)
71+
72+
$(P These are simple pointers to data.
73+
A pointer can manipulate a block of multiple values. Accessing more
74+
than one value cannot be
75+
$(DDLINK spec/memory-safe-d, Memory-Safe-D-Spec, `@safe`) as it
76+
requires $(RELATIVE_LINK2 pointer-arithmetic, pointer arithmetic).
77+
This is supported for interfacing with C and for
4878
specialized systems work.
49-
There is no length associated with it, and so there is no way for the
79+
A pointer has no length associated with it, so there is no way for the
5080
compiler or runtime to do bounds checking, etc., on it.
51-
Most conventional uses for pointers can be replaced with
81+
)
82+
83+
$(BEST_PRACTICE Most conventional uses for pointers can be replaced with
5284
dynamic arrays, $(D out) and $(D ref) parameters,
5385
and reference types.
5486
)

0 commit comments

Comments
 (0)