Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.


9.3.3 Array pointers

When you declare an array, the address of the (beginning of the) array is given by the variable name without square brackets. Consider the following program:

DEF a[10]:ARRAY OF INT

PROC main()
  DEF ptr:PTR TO INT, i
  FOR i:=0 TO 9
    a[i]:=i
  ENDFOR
  ptr:=a
  ptr++
  ptr[]:=22
  FOR i:=0 TO 9
    WriteF('a[\d] is \d\n', i, a[i])
  ENDFOR
ENDPROC

Here's the output from it:

a[0] is 0
a[1] is 22
a[2] is 2
a[3] is 3
a[4] is 4
a[5] is 5
a[6] is 6
a[7] is 7
a[8] is 8
a[9] is 9

You should notice that the second element of the array has been changed using the pointer. The assignment to ptr initialises it to point to the start of the array a, and then the ptr++ statement increments ptr to point to the next element of the array. It is vital that ptr is declared as PTR TO INT since the array is an ARRAY OF INT. The [] is used to dereference ptr and therefore 22 is stored in the second element of the array. In fact, the ptr can be used in exactly the same way as an array, so ptr[1] would be the next (or third element) of the array a. Also, since ptr points to the second element of a, negative values may legitimately be used as the index, and ptr[-1] is the first element of a.

In fact, the following declarations are identical except the first reserves an appropriate amount of memory for the array whereas the second relies on you having done this somewhere else in the program.

  DEF a[20]:ARRAY OF INT

  DEF a:PTR TO INT

The following diagram is similar to the diagrams given earlier (see 9.2.1 Addresses). It is an illustration of an array, a, which was declared to be an array of twenty INTs.

    +--------+
    |Variable|
    |  'a'   |
    |--------|
    | Address+----*
    +--------+     \
                    \
                     \
         +-------+ +--\----+ +-------+     +-------+ +-------+
         |Unknown| | a[0]  | | a[1]  |     | a[19] | |Unknown|
Memory:  |+-----+| |+-----+| |+-----+| ... |+-----+| |+-----+|
         || XXX || || INT || || INT ||     || INT || || XXX ||
         +=======+ +=======+ +=======+     +=======+ +=======+

As you can see, the variable a is a pointer to the reserved chunk of memory which contains the array elements. Parts of memory that aren't between a[0] and a[19] are marked as `Unknown' because they are not part of the array. This memory should therefore not be accessed using the array a.


Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.