Passing pointers to functions, continued
Instead, we need to pass a 'reference' to the two integers to be
interchanged.
We need to give the swap() function "access" to the variables
a and b,
so that swap() may modify those variables:
#include <stdio.h>
void swap(int *ip, int *jp)
{
int temp;
temp = *ip; // swap's temp is now 3
*ip = *jp; // main's variable a is now 5
*jp = temp; // main's variable b is now 3
}
int main(int argc, char *argv[])
{
int a=3, b=5;
printf("before a=%i, b=%i\n", a, b);
swap(&a, &b); // pass pointers to our local variables
printf("after a=%i, b=%i\n", a, b);
return 0;
}
before a=3, b=5
after a=5, b=3
|
Much better! Of note:
- The function swap() is now dealing with the original variables,
rather than new copies of their values.
- A function may permit another function to modify its variables,
by passing pointers to those variables.
- The receiving function now modifies what those pointers point to.
CITS2002 Systems Programming, Lecture 12, p2, 28th August 2024.
|