Broken code:
#include <stdio.h>
void swap(int a, int b)
int main(void)
{
int x = 1;
int y = 2;
("x is %i, y is %i\n", x, y);
printf(x,y);
swap("x is %i, y is %i\n", x, y);
printf}
void swap(int a, int b)
{
int tmp = a;
= b;
a = tmp;
b }
a
and b
are only copies of x
and y
.A fixed swap()
function needs to use pointers to modify the original x
and y
variables:
#include <stdio.h>
void swap(int *a, int *b)
int main(void)
{
int x = 1;
int y = 2;
("x is %i, y is %i\n", x, y);
printf(&x,&y);
swap("x is %i, y is %i\n", x, y);
printf}
void swap(int *a, int *b) // Address of x and y
{
int tmp = *a; // Store the value at the address in a in tmp
*a = *b; // Store the value at the address in location b in the value at location a
*b = tmp; // Store the value in tmp in the value at location b
}
main()