1-D Arrays
C array
- At declaration, only the number of elements wanted is given not an
index range.
- The index range in C is from 0 to number of elements - 1. No choice.
- The name of the array represents ("holds") the address of the first
element in the array.
- You can use both [] notation (like most other languages use) or you may
use pointer notation and pointer arithmetic. For the 210 class, you use
ONLY [] notation unless I specifically ask you to use pointer notation.
- You may initialize your array at the time of declaration; however, if
you don't initialize the array yourself, it is NOT initialized.
- While under certain conditions, the C compiler will give you a default
value for the size of the array, this is a very BAD habit to get into.
Always, give the size of the array.
- All arrays are passed to functions as in-out parameters. There is no
other choice for passing an entire array in C.
- The size of the first dimension is not required in the function prototype
or the function header. The declared size of all other dimensions MUST
be shown in both the prototype and the function header.
Declaration
#define MAX 20
int numbers[10], vals[MAX], others[MAX*2 + 3];
float wages[100];
char letters[24];
int temp_array[5] = {1, 3, 5, 6, 100};
int another[100] = {0, 1, 3, 6, 9};
char grades[] = {'a', 'b', 'c', 'd', 'f'};
Access
Single element
numbers[0] = 2;
letters[23] = 'c';
wages[135] = 5.15; /* is there a problem here */
Whole array
Not possible. You may only access an array 1 element at a time.
another = numbers; Is not a valid statement. What this says is give
the starting address of numbers to the array another. This will not
"copy" the values in numbers into the first elements of another. Don't
even try it.
Passing arrays to functions.
pass_whole_array_in_only(numbers, low_index, high_index);
pass_whole_array_inout_out(numbers, low_index, high_index);
Receiving arrays to functions
void pass_whole_array_in_only(int array[], int low, int high);
or void pass_whole_array_in_only(int [], int, int);
or void pass_whole_array_in_only(int *, int, int);
/*Don't use the 3rd method unless specifically requested to do so*/
void pass_whole_array-inout_out(int array[], int low, int high);
or void pass_whole_array-inout_out(int [], int, int);
or void pass_whole_array-inout_out(int *, int, int);
Accessing arrays passed as parameters is exactly like accessing them
within the scope in which they were declared. (See access examples above.)
Passing part of an array to a function
min = min4(numbers[1], numbers[2], numbers[3], numbers[4]);
get_int(&number[1]);
fill_array(numbers, 3, 7); /* purpose is to fill from index 3 to index 7
(5 elements are changed) */
NOTE: min4() prototype and header have not changed at all
get_int() prototype and header have not changed at all
fill_array(int [], int, int) could be used to fill the whole array
if low = 0 and high = MAX_size - 1