30 likes | 94 Views
Part 1 Landscape. Hannu Laine. Comparing pointer parameters and reference parameters. Pointer parameters. Reference parameters. //prototype of swap void swap(int *a, int *b); //application void main(void) { in number1 = 1, number2 = 2; swap(&number1, &number2);
E N D
Part 1 Landscape Hannu Laine
Comparing pointer parameters and reference parameters Pointer parameters Reference parameters • //prototype of swap • void swap(int *a, int *b); • //application • void main(void) { • in number1 = 1, number2 = 2; • swap(&number1, &number2); • printf("%d %d", number1, number2); • } • //implementation of swap • void swap(int *a, int *b) { • int aux; • aux = *a; • *a = *b; • *b = aux; • } • //prototype of swap • void swap(int &a, int &b); • //application • void main(void) { • in number1 = 1, number2 = 2; • swap(number1, number2); //pointers are • // passed instead of values • printf("%d %d", number1, number2); • } • //implementation of swap • void swap(int &a, int &b) { • int aux; • aux = a; //deferencing is used internally • a = b; //with a and b • b = aux; • } Back
Returning a pointer and returning a reference Returning a pointer Returning a reference • //prototype of a function • int *getMax(int *arr, int n); • //application • int main(void) { • int maxValue; • int array[6] = {3, 5, 2, 8, 6, 7}; • printf (”%d”, *getMax(array, 6)); //Right value • maxValue = *getMax(array, 6); • *getMax (array, 6) = *getMax (array, 6) *10; • //Left value • } • //implementation getMax • int *getMax(int *arr, int n) { • int i, maxi = 0; • for (i = 1 ; i < n ; i++) • if (arr [ i ] > arr [ maxi ] ) • maxi = i; • return &arr[maxi]; • } • //prototype of a function • int &getMax(int *arr, int n); • //application • int main(void) { • int maxValue; • int array[6] = {3, 5, 2, 8, 6, 7}; • printf (”%d”, getMax(array, 6)); //Right value • maxValue = getMax(array, 6); • getMax(array, 6) = getMax(array, 6) *10; //Left value • } • //implementation getMax • int &getMax(int *arr, int n) { • int i, maxi = 0; • for (i = 1 ; i < n ; i++) • if (arr [ i ] > arr [ maxi ] ) • maxi = i; • return arr[maxi]; • } Back