Download presentation
Presentation is loading. Please wait.
Published byMicheal Humble Modified over 9 years ago
1
Call By Address Parameters (Pointers) Chapter 5
2
Functions that “return” more than a single value What if we need more than one value to be returned from a function? For example, imagine we need a function to to calculate how many quarters, dimes, nickels and pennies should be given when making change. Call by address parameters allow a function to “return” more than a single value Rather than passing the value of a parameter to a function the address of a variable is passed to the function Any changes made by the function are then made to the memory location of that variable
3
Declaration of a Pointer Variable A pointer variable holds the memory address of another variable. By convention, many programmers name a pointer variable with the same name as the variable "pointed" to, but starting with a p_ A pointer variable is always declared to be the same type as the variable it points to and must have a * (an asterisk) in front of it, to identify it as a pointer. For example, to declare a pointer to point to an int variable named num, the declaration would be: int *p_num; /* pointer to int variable num */
4
Assignment of a Pointer Variable To assign p_num the address of num (i.e. to "point" to num), use the following assignment statement: p_num = # Translated, this means: p_num is assigned the value of the address of the variable num
5
Pointers Exercise Write a function sort 2 that is passed 2 integer values and returns the values in ascending order as shown in main below: void sort2(int n1, int n2, int *p_num1, int *p_num2); main() {int int1, int2, first, second; printf(“Enter 2 integers: “); scanf(“%d %d”, &int1, &int2); sort2(int1, int2, &first, &second); printf(“First: %d, Second: %d\n”,first, second); }
6
Pointers Exercise Solution void sort2(int n1, int n2, int *p_num1, int *p_num2){ if (n1 <= n2) { *p_num1 = n1; *p_num2 = n2; } else { *p_num1 = n2; *p_num2 = n1; }
7
Pointer Exercise Write a function to calculate how many quarters, dimes, nickels and pennies should be given when making change to be used in program shown below: void makechange(double, int *, int *, int *, int *); main() {double amount; int numqtrs, numdimes, numnickels, numpennies; printf("Amount of money (in dollars and cents): $"); scanf("%lf", &amount); makechange(amount, &numqtrs, &numdimes, &numnickels, &numpennies); printf(“Change: %d quarters,%d dimes,", numqtrs, numdimes); printf("%d nickels, %d pennies\n", numnickels, numpennies); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.