\(4.8.\)Pointer and Input, Output Control

1.Pointer

  We use A-instruction to point to a certain address. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//   for(i = 0; i < n; i ++) {
// arr[i] = -1
// }

// suppose arr = 100 and n = 10

//initialize
@100
D = A
@arr
M = D

@10
D = A
@n
M = D

@i
M = 0

//iteration

(LOOP)
@i
D = M
@n
D = D - M
@END
D;JEQ

//RAM[arr + i] = -1
@i
D = M
@arr
A = D + M
M = -1
@i
M = M + 1

@LOOP
0;JMP

(END)
@END
0;JMP

  The key step in the program is A = D + M, M = -1:

  • The A = D + M point the address of arr to the base address of arr(the initial address, 100) plus i, which match the expression arr + i.

  • By the time we say M equals -1, the register that will be affected is the register in A address.

  • Variables that store memory addresses like arr + i are called pointers.

  • Typical pointer semantics:"set the address register to the contents of some memory register"

2.Screen input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//for (i = 0; i < n; i ++)
// draw 16 black pixels at the
// beginning of row i

// addr = SCREEN
// n = RAM[0]
// i = 0
// LOOP:
// if i > n goto END
// RAM[addr] = -1 1111111111111111
// addr = addr + 32
// i = i + 1
// goto LOOP

@SCREEN
D = A
@addr
M = D

@R0
D = M
@n
M = D

@i
M = 0

(LOOP)
@i
D = M
@n
D = D - M
@END
D; JGT

@addr
A = M
M = -1

@i
M = M + 1
@32
D = A
@addr
M = M + D
(LOOP)
0; JMP

(END)
@END
0; JMP