- How to swap two elements of an array using a function
- Why the addresses of array elements must be passed using
&arr[i]and&arr[j] - How to modify original array values using pointer dereferencing
- Why a temporary variable is required during swapping
- How pointer parameters allow a function to change variables in the caller
- How to validate array indexes before swapping
How Pointer-Based Swapping Works
Swapping means exchanging the values stored at two memory locations. In an array, each element has its own address. To swap arr[i] and arr[j], the program must exchange the values stored at &arr[i] and &arr[j].
A normal function cannot permanently change the caller's variables if it receives only their values, because C passes arguments by value. To change the original array elements, the function must receive their addresses. Pointer parameters such as int *a and int *b store those addresses, and *a and *b access the actual values stored there.
The swapping process uses a temporary variable. First, the value at the first address is saved in temp. Then the value at the second address is copied into the first location. Finally, the temporary value is copied into the second location. After these three assignments, the two array elements are exchanged.
💡 In one line: Pass the addresses of two array elements to a swap function, then exchange their values using temp = *a, *a = *b, and *b = temp.
The Three Steps of Swapping
| Step | Pointer operation | Effect |
|---|---|---|
| 1. Pass element addresses | swap(&arr[i], &arr[j]); | The function receives the memory addresses of the two elements |
| 2. Save the first value | int temp = *a; | The original value of the first element is stored safely |
| 3. Exchange the values | *a = *b; and *b = temp; | The second value moves to the first location and the saved value moves to the second location |
The temporary variable is essential. If you directly write *a = *b; followed by *b = *a;, both locations will end up with the same value, because the original value of *a would already be lost after the first assignment.
Pointer-based swapping is widely used in sorting algorithms such as bubble sort, selection sort, and quicksort. In those algorithms, two array elements are repeatedly exchanged until the entire array becomes sorted.
Complete C Program
Program: swap two elements in an array using pointers
#include <stdio.h>
#define MAX 100
/* Swap two integers using pointers. */
void swap(int *a, int *b) {
int temp;
temp = *a; /* save the value at the first address */
*a = *b; /* copy the second value to the first address */
*b = temp; /* copy the saved value to the second address */
}
/* Swap two elements of an array by index. */
void swap_array_elements(int arr[], int i, int j) {
if (i < 0 || j < 0 || i >= MAX || j >= MAX || i == j) {
printf("Invalid indexes. No swap performed.\n");
return;
}
swap(&arr[i], &arr[j]);
}
int main(void) {
int arr[MAX];
int n, i, j, k;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (k = 0; k < n; k++) {
if (scanf("%d", &arr[k]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
printf("Enter the first index to swap: ");
if (scanf("%d", &i) != 1 || i < 0 || i >= n) {
printf("Invalid first index.\n");
return 1;
}
printf("Enter the second index to swap: ");
if (scanf("%d", &j) != 1 || j < 0 || j >= n) {
printf("Invalid second index.\n");
return 1;
}
printf("\nArray before swapping:\n");
for (k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
swap_array_elements(arr, i, j);
printf("\nArray after swapping:\n");
for (k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
return 0;
}
Program Output
How many elements? 5
Enter 5 integers:
10 20 30 40 50
Enter the first index to swap: 1
Enter the second index to swap: 3
Array before swapping:
10 20 30 40 50
Array after swapping:
10 40 30 20 50
A second run, where the same index is entered twice:
How many elements? 5
Enter 5 integers:
10 20 30 40 50
Enter the first index to swap: 2
Enter the second index to swap: 2
Invalid indexes. No swap performed.
Array before swapping:
10 20 30 40 50
Array after swapping:
10 20 30 40 50
In the first run, the elements at index 1 and index 3 are exchanged. The value 20 moves to index 3, and the value 40 moves to index 1. In the second run, both indexes are the same, so the program reports that no swap is needed and the array remains unchanged.
Step-by-Step Explanation
Let us understand how the swap function changes the original array.
1. The swap function signature
void swap(int *a, int *b) receives two integer pointers. These pointers hold the addresses of the two array elements that need to be exchanged. The return type is void because the function does not return a value; it modifies the original memory locations directly.
2. Passing addresses from main
The call swap(&arr[i], &arr[j]); sends the addresses of the two required elements. The address-of operator & is necessary because the function must know where the values are stored in memory. Without addresses, the function would receive only copies of the values and could not change the original array.
3. Saving the first value
Inside the function, temp = *a; reads the value stored at the address held by a and saves it in temp. For example, if *a is 20, then temp becomes 20.
4. Copying the second value
*a = *b; copies the value stored at the address held by b into the location pointed to by a. If *b is 40, then the first element becomes 40.
5. Restoring the saved value
*b = temp; copies the saved value back into the second location. Since temp contains the original first value, the second element now receives that value. The swap is complete.
6. Example trace
Suppose the array is [10, 20, 30, 40, 50], and the user wants to swap index 1 and index 3:
- Before swapping:
arr[1] = 20andarr[3] = 40. - The function receives
a = &arr[1]andb = &arr[3]. temp = *a, sotemp = 20.*a = *b, soarr[1] = 40.*b = temp, soarr[3] = 20.- After swapping:
[10, 40, 30, 20, 50].
7. Why indexes are validated
The program checks whether the entered indexes are within the valid range from 0 to n - 1. This prevents accessing memory outside the array, which can cause unpredictable behavior or a program crash. It also checks whether both indexes are the same, because swapping an element with itself has no effect.
8. Swapping without a temporary variable
It is possible to swap two integers without a temporary variable using arithmetic:
void swap_without_temp(int *a, int *b) {
if (a == b) return;
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
However, this method can cause integer overflow when the values are very large. The temporary-variable method is simpler, safer, and easier to understand, so it is preferred in most programs.
9. Why pointer swapping is important
Pointer swapping demonstrates one of the most important uses of pointers: allowing a function to modify data that belongs to the caller. This concept is used in sorting, linked lists, dynamic memory management, and many library functions.
10. Complexity summary
Time complexity is O(1), because swapping two elements requires a fixed number of operations regardless of the array size. Space complexity is also O(1), because only one temporary variable and two pointer parameters are used.
🎯 Remember this: To swap array elements through a function, pass their addresses using &arr[i] and &arr[j]. Inside the function, exchange the values using a temporary variable and dereferencing: temp = *a, *a = *b, and *b = temp.
Frequently Asked Questions
1. Why do we pass &arr[i] instead of arr[i]?
We pass &arr[i] because the swap function needs the address of the array element to modify it permanently. If we pass arr[i], the function receives only a copy of the value, and any change made inside the function will not affect the original array.
2. What do *a and *b mean?
*a and *b dereference the pointers, meaning they access the values stored at the addresses held by a and b. Therefore, assigning to *a or *b changes the original array elements.
3. Why is a temporary variable needed?
A temporary variable preserves the original value of the first element before it is overwritten. Without it, the original value would be lost after *a = *b;, and both elements would end up with the same value.
4. What happens if both indexes are the same?
If both indexes are the same, the element is swapped with itself, so the array does not change. The program checks for this condition and prints a message instead of performing an unnecessary swap.
5. Can this swap function be used in sorting programs?
Yes. The same swap() function can be used in bubble sort, selection sort, insertion sort variants, and quicksort. Sorting algorithms repeatedly call swap to rearrange array elements into the required order.
6. What is the time complexity of swapping two array elements?
The time complexity is O(1), because the swap involves only three assignments and does not depend on the size of the array. The space complexity is also O(1), since only one temporary variable is required.
💡 Tip: After implementing this program, try using the same swap() function to reverse an entire array. Swap the first element with the last, the second with the second-last, and continue until you reach the middle.