Implementing the Swap Logic
Now let's implement the actual swap logic using pointers.
Assigning Addresses to Pointers
First, we need to make our pointers point to our variables by assigning the addresses of a
and b
to ptra
and ptrb
respectively:
// Assign addresses to pointers
ptra = &a;
ptrb = &b;
The Swap Algorithm Using Pointers
The key to swapping values with pointers is to manipulate the values at the memory locations, not just the pointers themselves. Here's how we'll do it:
- Store the value of
a
(accessed via *ptra
) in the temporary variable temp
- Assign the value of
b
(accessed via *ptrb
) to a
(by using *ptra
)
- Assign the temporary value (original value of
a
) to b
(by using *ptrb
)
Update your main.c
file by adding the following code where indicated in the previous step:
#include <stdio.h>
int main() {
// Declare variables
int a, b;
int *ptra, *ptrb;
int temp;
// Get input from user
printf("Enter value for a: ");
scanf("%d", &a);
printf("Enter value for b: ");
scanf("%d", &b);
// Display original values
printf("\nOriginal values:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
// Assign addresses to pointers
ptra = &a;
ptrb = &b;
// Display memory addresses (optional but helpful for understanding)
printf("\nMemory addresses:\n");
printf("Address of a: %p\n", ptra);
printf("Address of b: %p\n", ptrb);
// Swap the values using pointers
temp = *ptra; // Store value of a in temp
*ptra = *ptrb; // Assign value of b to a
*ptrb = temp; // Assign original value of a to b
// Display swapped values
printf("\nAfter swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Understanding the Swap Logic
Let's understand exactly how the swap works:
temp = *ptra;
- The *
operator dereferences the pointer, accessing the value at the memory location. This line stores the value of a
in temp
.
*ptra = *ptrb;
- This assigns the value of b
to the memory location of a
, effectively changing a
's value.
*ptrb = temp;
- This assigns the original value of a
(stored in temp
) to the memory location of b
, completing the swap.
After these operations, the variables a
and b
have exchanged values without directly modifying them - we only modified the values at their memory locations.