How to swap two arrays using pointers in C

In this article, we are going to learn how to swap two arrays using pointers in C language with example. We will take array element input from the user using the array and iterate over the array and arrays element to function to swap them.

1. How to swap two arrays using pointers


In this example, we will learn how to swap two arrays using a pointer. We are asking users to input elements of the array using a loop and iterating over the array element of the array to swap. We are going to use the bitwise XOR operator to write below program logic. This Logic can be used to swap two arrays of different lengths using pointers in C programming.

#include <stdio.h>

#define SIZE 100 

void swapArrayElements(int * Arr1, int * Arr2, int size)
{

    int *Arr1lastIndex = (Arr1 + (size - 1));

    int * Arr2lastIndex   = (Arr2 + (size - 1));

    while(Arr1 <= Arr1lastIndex && Arr2 <= Arr2lastIndex)
    {
        *Arr1 ^= *Arr2;
        *Arr2   ^= *Arr1;
        *Arr1 ^= *Arr2;

        Arr1++;
        Arr2++;
    }
}

int main()
{
    int arr1[SIZE];
	int arr2[SIZE];
    int size;
	
    int * ptr1 = arr1; 
	int * ptr2 = arr2;	

    printf("Please enter size of array(max 100): ");
    scanf("%d", &size);

    printf("Please enter elements of array1:\n");
    for (int i = 0; i < size; i++)
    {
		scanf("%d", (ptr1 + i));   
    }
	
	printf("Please enter elements of array2:\n");
    for (int i = 0; i < size; i++)
    {
		scanf("%d", (ptr2 + i));   
    }


    printf("The elements entered by user are: \n");
    for (int k = 0; k < size; k++)
    {
        printf("Array1[%d]= %d, ",k, *ptr1);
        ptr1++;
    }
	for (int k = 0; k < size; k++)
    {
        printf("Array2[%d]= %d, ",k, *ptr2);
        ptr2++;
    }
	
	 ptr1 = arr1;
	 ptr2 = arr2;
	  
	swapArrayElements(ptr1,ptr2,size);
	
	printf("The elements of Swapped Arrays are: \n");
    for (int k = 0; k < size; k++)
    {
        printf("Array1[%d]= %d, ",k, *ptr1);
        ptr1++;
    }
	for (int k = 0; k < size; k++)
    {
        printf("Array2[%d]= %d, ",k, *ptr2);
        ptr2++;
    }

    return 0;
}

Output

Please enter size of array(max 100): 5
Please enter elements of array1:
1
2
3
4
5
Please enter elements of array2:
0
9
8
7
6

The elements entered by user are: 
Array1[0]= 1, Array1[1]= 2, Array1[2]= 3, Array1[3]= 4, Array1[4]= 5, 
Array2[0]= 0, Array2[1]= 9, Array2[2]= 8, Array2[3]= 7, Array2[4]= 6, 
The elements of Swapped Arrays are: 
Array1[0]= 0, Array1[1]= 9, Array1[2]= 8, Array1[3]= 7, Array1[4]= 6, 
Array2[0]= 1, Array2[1]= 2, Array2[2]= 3, Array2[3]= 4, Array2[4]= 5,