Pointers - 3.2 PARAMETER PASSING USING POINTERS
4.2 PARAMETER PASSING USING POINTERS
What do you understand by parameter passing? It is important when you use functions. How does parameter passing relate to pointers?
Pointers are normally passed to functions. This way, we pass the address to a local variable that points to the actual location of the data item by the calling program. The value that is changed in the function will change the value at the actual location. This method of passing is known as passing by reference or reference passing.
Program 4.1 #include #include #include #include float calculateTotal1(int, int, int, float); float calculateTotal2(int, int, int *, float *); int main(){ int total1, total2, i, total; float average1, average2, average; total1 = total2 = 0; average1 = average2 = 0.0; for (i=1;i<=9;i++) total +=1; average = (float) total /8; printf(" %d %.2f\n",i, average); calculateTotal1(1, 9, total1, average1); printf("total1 = %d, average1 = %.2f\n", total1,average1); calculateTotal2(1, 9, &total2, &average2); printf("total2 = %d, average2 = %.2f\n", total2, average2); getch(); } float calculateTotal1(int start, int finish, int total, float average) { int i; for (i = start; i <= finish; i++) total +=i; average = (float) total / (finish - start + 1); } float calculateTotal2(int start, int finish, int *total, float *average) { int i; for (i = start; i <= finish; i++) *total +=i; *average = (float) *total / (finish - start + 1); } | ||
![]() | ![]() | ![]() |
When the calculateTotal2() function is called, the address for total1 (which is &total1) is assigned to the total pointer. This means that total points to the actual location of total1 in the calling program statement. In the same way, the average pointer points to the location of average2. Figure 4.4 shown the relationship between variables when the calculateTotal2() function is called.
Output : total 1 = 0, average1 =0.00 total2 = 45, average2 = 5.00![]() |
Figure 4.4: Relationship between variables during the calculateTotal2 function call
|
Then, the body of the calculateTotal2() function performs that calculation and changes the value for the variables that are pointed by total and average. This means that the actual value that is changed, is the value stored in the actual total2 location (that is pointed by total) and average2 (that is pointed by average). When this function ends, the values of total2 and average2 has been changed to the new values as calculated during the execution of that function.
| ||||||||||
Look at the outline of following function:
|
Comments