CSC195, Class 17: Arrays Overview: * Representing arrays * Key array operations * Lab Notes: * Yes, I know the reading emphasized pointers. We'll still emphasize arrays for today (and tomorrow). * Read Gries on arrays * Doing well in the swim meet does not excuse you from class ---------------------------------------- What is an array? * Implementation perspective: A contiguous block of storage * Functional perspective: What operations do you expect arrays/"vectors" to provide? + get(array a, int position): Get a value from the array "constant time" + set(array a, int position, SomeType newvalue): Set a value in the array "constant time" + a = create(int length) + destroy(a) + length(a) * Fun things to build once you have ^ + find(a, value)? + remove(array a, int position) If you implement an array as a contiguous block of storage, it's pretty easy to find the nth element of an array of identical type things If a starts at position p a[i] is at position p+i*sizeof(thing) How do you find the length of the array? * Store a special value at the end of the array (e.g., strings in C) * Store the length at the beginning of the array or somewhere nearby (e.g., Pascal, Java, ...) * Don't let programmers choose array lengths. Use a fixed length. * Store the end in memory * The C solution: "Smart programmers know to keep track of the lengths of their own arrays". What fun things can you do with arrays? * Assign to them a[i] = whatever; * Use them whatever = a[i]; * Declare new ones int a[100]; * Declare and initialize new ones int a[5] = { 3, 2, 4, 1, 6 }; Arrays can have more than one dimension * Declare new ones int b[10][5]; * Assign to them: b[i][j] = 3; * Use them whatever = b[i][j] * Initialize them: See the lab Two simplest ways to fit a 10x5 array in one contiguous block of memory ROW-MAJOR ORDER b[0][0] b[0][1] ... b[0][4] b[1][0] b[1][1] ... b[1][4] ... Or COLUMN-MAJOR ORDER b[0][0] b[1][0] ... b[9][0] b[0][1] b[1][1] ... b[9][1] ... C uses ROW-MAJOR order. Where is b[i][j]? "base of b" + i*row_size*sizeof(elt) + j*sizeof(elt) Another mechanisms: Use pointers WHAT IS THE BIGGEST DISADVANTAGE OF THESE MULTI-DIMENSIONAL ARRAYS?