Expert C Programming

(Jeff_L) #1
compiler symbol table has a as address 9980

runtime step 1: get value i, scale it by the size of a row (6 bytes here), and add it to 9980

runtime step 2: get value j, scale it by the size of an element (1 byte here), add it to previous step's
result

runtime step 3: get the contents from address (9980 + i*scale-factor1 + j*scale-factor2)

a[i][j]

The definition char a[4][6] says a is an array [4], each element of which is an array [6], each
element of which is a char. So the look-up goes to the i'th of the four arrays (steps over i six-byte
arrays to get there), then gets the j'th character in that array.

Table 10-2. char *p[4]—An Array of Pointers-to-String
char *p[4] —An Array of Pointers-to-String

compiler symbol table has p as address 4624

runtime step 1: get value i, scale it by the size of a pointer (4 bytes here), and add it to 4624

runtime step 2: get the contents from address (4624+ scaled value i), say '5081'

runtime step 3: get value j, scale it by the size of an element (1 byte here), add it to 5081

runtime step 4: get the contents from address (5081+j)

p[i][j]

The definition char * p[4] says p is an array [4], each element of which is a pointer-to-char. So
the look-up can't even be completed unless the pointers have been filled in to point to characters (or
arrays of characters). Assuming everything has been given a value, the look-up goes to the i'th
element of the array (each element is a pointer), retrieves the pointer value there, adds j to it, and
retrieves whatever is at that address.

This works because of rule 2 in Chapter 8: a subscript is always equivalent to an offset from a pointer.
Thus, turnip[i] selects an individual element, which happens to be a pointer; then applying
subscript [j] to this yields *(pointer + j), which reaches a single character. This is merely an
extension of a[2] and p[2] both evaluating to a character, as we saw in the previous chapter.

Using Pointers for Ragged Arrays


Iliffe vectors are an old compiler-writing technique, first used in Algol-60. They were originally used
to speed up array references, and on limited-memory machines to simplify keeping only part of an
array in main memory. Neither of these uses is as applicable on modern systems, but Iliffe vectors are
valuable in two other ways: for storing tables where the rows are different lengths, and for passing
arrays of strings in a function call. If you need to store 50 strings which can vary in length up to 255
characters, you could declare the following two-dimensional array:

Free download pdf