Notes on Arrays (Chapter 8) Declaring and referencing arrays (sections 8.1 and 8.2) Declaration and initialization: syntax: element-type array-array[size]; element-type array-array[size] = {initialization list}; example: int list[5]; /* list[0], list[1], list[2], list[3], list[4] */ int list[5] = {3, -2, 1, 0 , 2}; double x[8]; double x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.5, 14, -54.5}; Note: the array subscript starts with 0, then 1, 2, .... Subscripts and references: x[3]=25.0; sum = x[0]+x[1]; x[3] += 1.0; x[2] = x[0] + x[1]; i = 5; x[i+1]; x[i++]; x[(int)x[4]]; x[i]=x[i+1]; x[i-1]=x[i]; see code: array1.c Note: it is the programmer's responsiblity to verify that the subscript is within the declared range. otherwise ... Using ``for loop'' for sequential access (section 8.3) #define SIZE 10; int square[SIZE], i; for (i=0; i < SIZE; ++i) square[i] = i*i; see code: mean.c Using (individual) array elements as function arguments (section 8.4) example: void do_it(doubel arg1, double *arg2p, double *arg3p){ ... *arg2p = ... *arg3p = ... ... } ... do_it(x[0], &x[1], &x[2]); Array arguments (section 8.5) Question: how to write a function that have arrays as arguments. Formal array parametes: passes an array argument by passing the address of the its initial element. code: fill_array.c ``int list[]'' as formal parameter, stores the address of the initial array element. function call: fill_array(x, ...) or equivalently fill_array(&x[0], ...); code: fill_array2.c ``int list[]'' or ``int *list'' code: maxmin.c Note: the function manipulates the original arrays, ... may change the contents of the original array. Array as ``read-only'' input arguments only as an input to the function, the function does not intend to modify the array. syntax: const element-type array-name[] or const element-type *array-name code: get_max.c Returning an array result code: add_arrays.c note that: address-of operator (&) not used. stack: a data structure in which only the top element can be accessed. push: store an item in a stack. pop: remove a value from a stack. code: push_pop.c Search and sorting an array (section 8.6) code: search.c select_sort.c Multidimensional array (section 8.7) declaration: element-type aname[size_1][size_2]; element-type aname[][size_2]; examples: int a[2][3]; int a[2][3] = {{1,2,3}, {4,5,6}}; /* initialized */ Notes: C stores arrays in a ``row-major order'', row 0 first, then row 1, and so forth. the size of the first array dimension (the number of rows) is only the size that can be omitted -- #define N 5 double a[N][N]; int row, col; for (row = 0; row < N; row++) /* nested for loops */ for (col = 0; col < N; col++) if (row == col) a[row][col]=1.0; else a[row][col]=0.0; -- void process_matrix(int a_in[][4], int a_out[][4], int nrows); Note: as for one-dimensional array, the value actually stored in an array formal parameters is the address of the initial elements of the actual arguments. code: add_matrices.c