Beispiel zur Verwendung von Zeigern
Da Zeiger in BASIC-Sprachen recht selten sind, sei hier noch ein einfaches Beispiel im Vergleich zur Programmiersprache C gegeben, das die Verwendung der Pointer verdeutlicht: C-Quelltext:
1 int main (void)
2 {
3 int a; /* integer variable */
4 int b[3]; /* integer array */
5 int* p1; /* pointer to integer variable */
6 int* p2[3] /* array of integer pointers */
7
8 a = 0; /* a is set to 0 */
9 p1 = &a; /* p1 points to a */
10 *p1 = 5; /* a is set to 5 */
11 b[0] = *p1; /* b[0] is set to the value of the variable p1 is
pointing at (a) */
12 p2[0] = & b[0]; /* p2[0] contains the address of b[0] */
13 *p2[0] = 7; /* the value p2[0] is pointing at (b[0]) is set to 7 */
14 p2[0][1] = 21; /* the value after the value p2[0] is pointing at
(b[1]) is set to 21 */
15 *p1 = p2[0][2]; /* a is set to the value of b[2] */
16 p1 = p2[0]; /* p2 is assigned the address p2[0] contains (b[0]) */
17 ++p1; /* p1 points now to the value after b[0] (b[1]) */
18
19 return (0);
20 } |
OWBasic-Quelltext:
1 DIM b[2] :! integer array
2 DIM &p2[2] :! array of integer pointers
3
4 a = 0 :! a is set to 0
5 &p1 = &a :! p1 points to a
6 p1 = 5 :! a is set to 5
7 b[0] = p1 :! b[0] is set to the value of the variable p1 is pointing
! at (a)
8 &~p2[0] = &b[0] :! p2[0] contains the address of b[0]
9 ~p2[0] = 7 :! the value p2[0] is pointing at (b[0]) is set to 7
10 ~p2[0][1] = 21 :! the value after the value p2[0] is pointing at
! (b[1]) is set
11 to 21
12 p1 = ~p2[0][2] :! a is set to the value of b[2]
13 &p1 = &~p2[0] :! p2 is assigned the address p2[0] contains (b[0])
14 INC &&p1 :! p1 points now to the value after b[0] (b[1])
15
16 END 0 |
|