Swapping Arrays – Solution

The two functions required from this month’s Exercise are show_arrays() and swap_arrays(). They’re not that difficult to code, meaning that you don’t need to use the dratted ** notation or perform any special tricks. Here’s how I solved the problem:

First, I used a SIZE constant to handle the number of elements in both arrays:

#define SIZE 5

This step isn’t required, but it does allow me flexibility later should both arrays change their number of elements.

Second, for each function, the values passed are pointers, i.e., the memory address where each array is located. The functions are prototyped similarly:

void show_arrays(int *y, int *z);
void swap_arrays(int *y, int *z);

Both are void functions because they don’t return anything; the arrays are manipulated in memory directly, which is the beauty of using pointers.

Third, the functions:

The show_arrays() function is necessary because otherwise I’d repeat the same chunk of code in the main() function. It uses two for loops to display each array’s elements:

void show_arrays(int *y, int *z)
{
    int x;

    printf("a =");
    for(x=0;x<SIZE;x++)
        printf(" %2d",y[x]);
    putchar('\n');
    printf("b =");
    for(x=0;x<SIZE;x++)
        printf(" %2d",z[x]);
    putchar('\n');
}

The %2d placeholder in each printf() statement keeps the output looking even between both arrays:

a =  2  4  6  8 10
b =  1  3  5  7  9

For the swap_arrays() function, here’s what I concocted:

void swap_arrays(int *y, int *z)
{
    int x,temp;

    for(x=0;x<SIZE;x++)
    {
        temp = y[x];
        y[x] = z[x];
        z[x] = temp;
    }
}

All you need to swap elements is a temporary storage int variable, temp. The value of y[x] element is saved to temp. Then z[x] is placed into y[x]. Finally, temp is placed into z[x]. This loop repeats for each element.

None of the variables in the function need to be pointers; only the array’s location is passed to the function as a pointer. Within the function, array notation can be used as a substitute. The temp variable isn’t a pointer because the array elements are int values, not pointers.

Click here to view the final code, which I find quite simple, but still a good exercise.

If you came up with another solution and the output is solid, congratulations!

2 thoughts on “Swapping Arrays – Solution

  1. If you were using malloc’ed pointers instead of actual arrays (probably more likely in real-life situations) you could just swap the pointers.

    If you are swapping integers (or chars) you can use XOR, eg.

    int a = 45; // 00101101
    int b = 99; // 01100011
    a = a ^ b; // 01001110
    b = a ^ b; // 00101101
    a = a ^ b; // 01100011

Leave a Reply