Java Reference
In-Depth Information
can be rearranged to:
address ( A [ i ])
= address ( A )
+
( i size ( Element ))
( low size ( Element ))
= address ( A )
( low size ( Element ))
+
( i size ( Element ))
We now note that low and size ( Element ) are normally compile-time constants,
so the expression ( low size ( Element )) can be reduced to a single value, bias .
Now we have:
address ( A [ i ])
= address ( A )
bias +
( i size ( Element ))
The address of an array is normally a static address (a global) or an o
set
relative to a frame pointer (a local). In either case, the bias value can be folded
into the array's address, forming a new address or frame o
ff
ff
set reduced by the
value of bias.
For example, if we declare an array int data[1900..2020], and assign
data an address of 10000, we get a bias value of 1900
size ( int )
=
7600.
In
computing the address of data[i] we compute 2400
+ i
4. This is exactly the
same form that we used for zero-based arrays.
Even if we allocate arrays in the heap (using new or malloc), we can use
the same approach. Rather than storing a pointer to the array's first element,
we store a pointer to its virtual ”zero-th” element (which is what subtracting
bias from the array address gives us). We do need to be careful when we assign
such arrays though; we must copy data beginning with first valid position in
the array. Still, indexing is far more common than copying, so this approach
is a very reasonable one.
Dynamic and Flex Arrays
Some languages, including Algol 60, Ada, Java, and C
support dynamic
arrays whose bounds and size are determined at runtime. When the scope of
a dynamic array is entered, its bounds and size are evaluated and fixed. Space
for the array is then allocated. The bounds of a dynamic array may include
parameters, variables, and expressions. For example, if C were extended to
allow dynamic arrays, a subprogram P might include the declaration:
int examScore[numOfStudents()];
Because the size of a dynamic array is not known at compile-time, we cannot
allocate space for it statically or in a frame. Instead, we must allocate space
either on the stack (just past the current frame) or in the heap (Java does this).
A pointer to the location of the array is stored in the scope in which the array
is declared. The size of the array (and perhaps its bounds) are also stored.
Using our above example, we would allocate space for examScores as shown
 
Search WWH ::




Custom Search