Java Reference
In-Depth Information
An array can allocated inmemory as a sequence of
N
identical data objects,
where
N
is determined by the declared size of the array. Hence in the above
example 100 consecutive integers are allocated.
An array, like all other data structures, has a size and possibly an alignment
requirement. An array's size is easily computed as:
size
(
array
)
=
NumberO f Elements
∗
size
(
Element
)
If the bounds of an array are included within its memory allocation (as is
the case for Java and C
), the array's memory requirement must be increased
accordingly.
Many processors impose an
alignment restriction
on data. For example,
integers, which are usually a word (four bytes) in size, often must be placed at
memory addresses that are a multiple of four. An array's alignment restriction
is that of its components. Thus an integer array must be word-aligned if
integers must be word-aligned.
Sometimes
padding
is needed to guarantee alignment of all array ele-
ments. For example, given the C declaration:
struct s {int a; char b;} ar[100];
each element of array ar (a struct named s) must be padded to a size of 8
bytes. This is necessary to guarantee that ar[i].a, an integer field, is always
word-aligned.
When arrays are copied, size information is used to determine how many
bytes to copy. Either a series of load
store instructions or a copy loop can be
used, depending on the size of the array.
In C, C
/
, all arrays are
zero-based
(the first element of an
array is always at position 0). This rule leads to a very simple formula for the
address of an array element:
++
,JavaandC
address
(
A
[
i
])
=
address
(
A
)
+
i
∗
size
(
Element
)
For example, using the declaration of ar as an array of struct s given above:
address
(
ar
[5])
=
address
(
ar
)
+
5
∗
size
(
s
)
=
address
(
ar
)
+
5
∗
8
=
address
(
ar
)
+
40
Computing the address of a field within an array of structures is easy too.
As discussed in Section 12.2.1:
address
(
struct
.
field
)
=
address
(
struct
)
+
o
ff
set
(
field
)