CS 455 Lecture Notes

Week Five, Tuesday: Arrays

Object Model Demo Program

I have created a small demo program to illustrate a container class using the example of bonsai. The source is in a single file for convenience because it's a minimal example program. The class Bonsai uses an array of Tree object pointers (a single bonsai has one pot and one or more trees). Using this pointer array technique, the trees can have knowledge of which bonsai they are associated with (and the same with the pot) by using a "void pointer" member data type.

The test program (an automated test sequence (ATS)) creates some trees, pots, and bonsai in order to exercise the various features of the model:

  // Construct some trees, pots, and bonsai for test:
  t1 = new Tree("Gnarly Old Oak", "Cork oak");
  t2 = new Tree("Curvey Old Oak", "Cork oak");
  t3 = new Tree("Straight Old Oak", "Cork oak");
  t4 = new Tree("Ancient Juniper", "Prostrata juniper");

  p1 = new Pot(16, "Oval", "Brown", "China");
  p2 = new Pot(13, "Rectangular", "Gray", "Japan");

  b1 = new Bonsai("Cork Oak Forest");
  b2 = new Bonsai("Venerable Shokan Juniper");
When run, the program outputs the single screenful of text as shown below:


Runtime session for the object model demonstration program.

For demonstration purposes, I had the Bonsai class destructor output the string " *kaboom* " to indicate the running of that function.

Declaring Arrays

  int c[12];

  int n[10] = {32, 27, 64, 19};

  int age[] = {13, 7, 9, 11, 7, 15, 34, 25};

  const int arraysize = 10;
  int j[arraysize];

  int size = 6;
  int k[size]; // Error! Java lets you use variables to declare arrays, but not C++.

  const int x; // Error! Constants must be initialized (because they can't be modified later).

  char string1[] = "first";  // String constructor feature of C and C++.
  char string2[] = {'f', 'i', 'r', 's', 't', '\0'};
  char* string3 = "first";

  char string4[20]; cin >> string4;

  static int array1[30];  // Function performance increase.

Passing Arrays to Functions

 void modifyArray(int b[], int arraySize);
  int hourlyTemperature[24];
  modifyArray(hourlyTemperature, 24);

Multi-dimensional Arrays

DD calls these multiple-subscripted arrays.
  int b[2][2] = {{1, 2}, {3, 4}};


This page established September 19, 1999; last updated September 27, 1999.