Programming Concept

Arrays, Collections & Dynamic Memory

Arrays, static vs dynamic memory, shallow/deep copies, multidimensional arrays, collections.

Chapter 7 (pp. 159–176) of Computer Science I.

Topics

SectionPageContent
Basic Usage160Declaring/indexing arrays.
Static & Dynamic Memory162Dynamic memory allocation; shallow vs deep copies.
Multidimensional Arrays1662-D and higher.
Other Collections167Lists, maps, etc.

Key Ideas

  • Static vs dynamic memory — most explicit in C with malloc/free and 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.