120 likes | 131 Views
CSci 160 Lecture 33. Martin van Bommel. Passing Arrays to Functions. Write a program to: Read in list of integers until sentinel 0 is entered Reverse the elements in the list Display list in reverse order int main(void) { int list[NElements]; GetIntegerArray(list);
E N D
CSci 160Lecture 33 Martin van Bommel
Passing Arrays to Functions • Write a program to: • Read in list of integers until sentinel 0 is entered • Reverse the elements in the list • Display list in reverse order int main(void) { int list[NElements]; GetIntegerArray(list); ReverseIntegerArray(list); PrintIntegerArray(list); }
Problems with Method • Two issues: • Number of elements in array?? • NElements or how many entered before sentinel • GetIntegerArray and ReverseIntegerArray must change values of argument arrays in main • up until now, values of arguments cannot be changed outside function
Generalize Number of Elements • Only wish to reverse and print actual number of elements, array contains more elements in declaration (maximum number) int list[MaxElements]; • Call actual number of elements effective size • Print and reverse must then be told size PrintIntegerArray(list, n);
Function Prototypes • Could write as void PrintIntegerArray(int array[MaxElements], int n); • Better to write void PrintIntegerArray(int array[], int n); • Then can pass array of any size • Also void ReverseIntegerArray(int array[], int n);
GetIntegerArray Prototype • GetIntegerArray has different structure • Don’t know effective size before call • GetIntegerArray determines effective size • Needs to know actual size to limit it • Also give it sentinel value for flexibility int GetIntegerArray(int array[], int max, int sentinel);
Mechanics of Array Parameters • When variable used as parameter, only its value is passed • When array name used as parameter, only base address of array sent to function • Function can then operate on the array in place without copying its contents • Storage for parameter array is shared with actual argument array
Implementing PrintIntegerArray void PrintIntegerArray(int array[], int n) { int i; for (i = 0; i < n; i++) { printf(”%d\n”, array[i]); } }
int GetIntegerArray(int array[], int max, int sentinel) { int n=0, value; printf(” ? ”); scanf(”%d”, &value); while (value != sentinel) { if (n == max) Error(”Too many items”); array[n] = value; n++; printf(” ? ”); scanf(”%d”, &value); } return (n); }
ReverseIntegerArray void ReverseIntegerArray(int array[], int n) { int i, limit; limit = n / 2; for (i = 0; i < limit; i++) { Swap values in array[i] and array[n - i - 1] } }
Swap Array Elements • Try Swap(array[i], array[n-i-1]); • No, because passing values • Must use Swap(array, i, n-i-1);
SwapIntegerElements void SwapIntegerElements(int array[], int p1, int p2) { int tmp; tmp = array[p1]; array[p1] = array[p2]; array[p2] = tmp; }