Lecture notes Wednesday 3/10/99
Arrays
- arrays:
- data structure consisting of related data items
- convenient for storing lists and tables of values
- same type and same name (related memory locations)
- size is static throughout program execution
- refer to elements:
- refer to particular element with subscript, e.g. c[1]
- watch out for off-by-one errors: subscripts start with 0 !!!
- fourth element vs. element 4
- if you ignore element 0 declare one more
- subscript must be an integer, but may be a variable or an expression
- declaration:
- state type and number of elements, e.g. int c[12]
- to reserve space in memory
- initialization:
- (by assignment) initialize each element
- (by input) initialize each element with scanf
- (by declaration) initializer list: comma-separated list in braces
- if less initializers than elements, then remainders are set to zero
- but if no initializer at all, then nothing is initialized
- possibility to combine declaration & initialization and omit size, e.g. int n[]={1,2}
- character arrays:
- a string is really an array of individual characters
- character arrays can be initialized with a string, e.g. char st[]="yes"
- ends with special null character '\0'
- can be input with scanf and omit &, e.g. scanf("%s", st), stops at first whitespace
- passing arrays to functions:
- to call: just specify the name, no brackets
- to receive: specify in parameter list, e.g. void f(int c[])
- call by reference (!) -> side effects
- but individual array elements (i.e. scalors) are passed call by value
- multiple-subscripted arrays:
- double-subscripted arrays are tables with rows and columns
- can be initialized by declaration using initializer list and braces
- to receive: subsequent subscripts are required, e.g. void f(int c[][3])
- a double-subscripted array is basically an array of single-subscripted arrays
- sidenotes:
- #define preprocessor directive: symbolic constants, all caps, replacement text
- common error: walking off the end of arrays
- storage class static for arrays reduces program execution time
- conversion specifier %p: prints address in hexadecimal
- the name is the address of the array in memory
- type qualifier const: to prevent modification
- sorting & searching