Remember, when a function is called, the values of arguments
are copied to the local variables of the function. In other words, a
function can not modify the original value.
Let's see what happens if you pass a pointer as the function argument.
#include <stdio.h> void func(int *p); int main (void) { int i = 10, j = 20; int *iPtr = &i; func(iPtr); func(&j); printf("In main: i is %d j is %d\n", i, j); } void func(int *p) { printf("In func: %d\n", *p); *p += 1; return; }The definition of func() tells that it receives a pointer to integer as an argument.
You can copy the source from /home/progClass/src/drift/pntrFunc.c.
Do you notice that the function can modify the value of local variables in main()? This is because the value of the pointer (address) is copied to the local pointer variable p. The address in the memory is unique, so the function can directly modify the local variable residing in another function through dereferencing the pointer.
Similarly, the following example shows a function which will create an array with random values. After the function call, the array a contains 10 random numbers.
int main(void) { double a[10], sum; sum = SumArray(a, 10); } double SumArray(double arr[], int size) { int i; double result = 0; for (i = 0; i < size; i++) { result += arr[i]; } return(result); }
Previously, we could returns only 1 value from a function. You can create a function which ``returns'' several calculated values by passing the address.
int main(void) { int a[10], sum, product; sumProdArray(a, 10, &sum, & product); } void SumProdArray(int *arr, int arrSize, int *sumAnswer, int *productAnswer) { int i, sumResult=0, prodResult=0; for (i = 0; i < arrSize; i++) { sumResult += arr[i]; prodResult *= arr[i]; } *sumAnswer = sumResult; *productAnswer = prodResult; return; }
Explanation: You prepare 2 variables (sum and product) which you want to receive the answers with.
Then the address of these two variables are passed to the function, and the function put the answers into the two variables.
int main(void) { double a[10]; srand48(time(NULL)); MakeRandArray(a, 10); } void MakeRandArray(double *a, int arrSize) { int i; for (i = 0; i < arrSize; i++) { a[i] = drand48(); } }