Chapter 7 (pp. 159–176) of Computer Science I.
Topics
| Section | Page | Content |
|---|---|---|
| Basic Usage | 160 | Declaring/indexing arrays. |
| Static & Dynamic Memory | 162 | Dynamic memory allocation; shallow vs deep copies. |
| Multidimensional Arrays | 166 | 2-D and higher. |
| Other Collections | 167 | Lists, maps, etc. |
Key Ideas
- Static vs dynamic memory — most explicit in C with
malloc/freeand contiguous 2-D arrays; abstracted away in Java/PHP. - Shallow vs deep copy — a classic bug source; copying a reference vs copying contents.
- PHP associative arrays generalize the collection idea with key-value / non-contiguous indices.
- Iterated with loops (foreach).
Examples
Find the maximum
max ← A[0]
for i from 1 to length(A) - 1:
if A[i] > max:
max ← A[i]
Shallow copy aliases the same data
B ← A // both names point to the same array
B[0] ← 99 // A[0] is now 99 too
A deep copy would duplicate each element instead.
In Java
int max = a[0];
for (int i = 1; i < a.length; i++)
if (a[i] > max) max = a[i];
int[] b = a; // b and a are the same array reference (shallow)
b[0] = 99; // a[0] is now 99 too
int[] c = a.clone(); // deep copy of a 1-D array
Citations
[1] Computer Science I, Ch. 7, pp. 159–176.