In this call
swapArray(a,b);
the argument expressions have the type int *
while the function parameters have the type int **
. There is no implicit conversion from the type int *
to the type int **
. So the compiler shall issue a diagnostic message.
In any case the swap function as it is implemented does not make sense. Your program has undefined behavior at least because it tries to swap pointers instead of the arrays themselves.
Take into account that arrays are not pointers though in expressions with rare exceptions they indeed are implicitly converted to pointers to their first elements.
To swap elements of two arrays you have to swap each pair of elemenets separatly.
And you have to supply the number of elements in the arrays. Otherwise the arrays need to have a sentinel value.
Here is a demonstrative program that shows how the function swap can be defined.
#include <stdio.h>
void printArr( const int a[], size_t n, const char *s )
{
printf( "%s:\t", s );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
void swapArray( int *a, int *b, size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
int tmp = a[i];
a[i] = b[i];
b[i] = tmp;
}
}
int main(void)
{
enum { N = 4 };
int a[N] = { 1, 2, 3, 4 };
int b[N] = { 5, 6, 7, 8 };
printArr( a, N, "a" );
printArr( b, N, "b" );
putchar( '\n' );
swapArray( a, b, N );
printArr( a, N, "a" );
printArr( b, N, "b" );
putchar( '\n' );
return 0;
}
Its output is
a: 1 2 3 4
b: 5 6 7 8
a: 5 6 7 8
b: 1 2 3 4
You could swap visual representations of original arrays using pointers. But in this case the arrays themselves will not be swapped.
Consider the following program.
#include <stdio.h>
void printArr( const int a[], size_t n, const char *s )
{
printf( "%s:\t", s );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
void swapArray( int **a, int **b )
{
int *tmp = *a;
*a = *b;
*b = tmp;
}
int main(void)
{
enum { N = 4 };
int a[N] = { 1, 2, 3, 4 };
int b[N] = { 5, 6, 7, 8 };
printArr( a, N, "a" );
printArr( b, N, "b" );
putchar( '\n' );
int *pa = a;
int *pb = b;
swapArray( &pa, &pb );
printArr( pa, N, "pa" );
printArr( pb, N, "pb" );
putchar( '\n' );
printArr( a, N, "a" );
printArr( b, N, "b" );
putchar( '\n' );
return 0;
}
Its output is
a: 1 2 3 4
b: 5 6 7 8
pa: 5 6 7 8
pb: 1 2 3 4
a: 1 2 3 4
b: 5 6 7 8
As you see the arrays were not swapped. However the pointers that point to first elements of the arrays were swapped. Using the pointers you can simulate swapping of arrays.
Opposite to C C++ has a template function std::swap
for arrays that can be called indeed simply like
std::swap( a, b );