Solution for Exercise 19-23
ex1923
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int x=100,y=33;
printf("Before swap: x=%d, y=%d\n",x,y);
swap(&x,&y);
printf("After swap: x=%d, y=%d\n",x,y);
return(0);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output
Before swap: x=100, y=33
After swap: x=33, y=100
Notes
* The swap() function is prototyped at Line 3 with the * operator for each of its arguments. Both are pointers, memory locations.
* The swap() function requires pointers, addresses, so at Line 10 it's called with variables a and b prefixed by the address-of operator, &. If you forget this step, the compiler reminds you rather rudely.
* It's also possible to declare pointer variables in the main() function and pass these arguments directly in the swap() function.
* Pointer notation must be used for the swap action at Lines 20, 21, and 22 in the swap() function. The temp variable, however, need not be a pointer; it just temporarily holds the values during the swap process.
Copyright © 1997-2025 by QPBC.
All rights reserved
