I had to swap array elements with call by reference to reduce the lines of code in my bigger project, and I am successful in swapping them but this code gives a bunch of warnings, how do I do this efficiently?
#include <stdio.h>
void swap(int *arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
int main(void)
{
int a[5] = {2, 4, 6, 2, 3};
swap(&a, 1, 2);
for (int i = 0; i < 5; i++)
{
printf("%d", a[i]);
}
return 0;
}
OUTPUT =>
swap_array.c: In function 'main':
swap_array.c:11:10: warning: passing argument 1 of 'swap' from incompatible pointer type [-Wincompatible-pointer-types]
11 | swap(&a, 1, 2);
| ^~
| |
| int (*)[5]
swap_array.c:2:16: note: expected 'int *' but argument is of type 'int (*)[5]'
2 | void swap(int *arr, int i, int j)
| ~~~~~^~~
26423
You declared an object of the array type int [5]
int a[5] = {2, 4, 6, 2, 3};
So the expression &a
has the pointer type int ( * )[5]
. But the function expects the first argument of the type int *
void swap(int *arr, int i, int j)
There is no implicit conversion from the type int ( * )[5]
to the type int *
. So the compiler issues an error message.
Instead you need to call the function like
swap(a, 1, 2);
In this case the array designator a
is implicitly converted to pointer to its first element of the type int *
and using the pointer arithmetic you can access elements of the array with the indices 1
and 2
.
However it is better to declare and define the function only with two parameters the following way
void swap( int *px, int *py )
{
int temp = *px
*px = *py;
*py = temp;
}
and call the function like
swap( a + 1, a + 2 );
In C passing by reference means passing objects indirectly through pointers to them. Thus dereferencing the pointers you can have a direct access to the objects pointed to by the pointers.
Pay attention to that for example the expression a[i]
is evaluated like *( a + i )
where the array designator a
is converted to pointer to its first element.