I'm trying passing an array to change its elements by reference.
Example:
Input element 1 = 4 / element 2 = 5 / element 3 = 6
Output element 1 = 6 / element 2 = 4 /element 3 = 5
Inside the swap function, the swapping is working but when I print the array in the main function, it prints the original array without swapping it.
Code bellow:
void swap1(int *n1, int *n2, int *n3)
{
int temp = *n3;
*n3 = *n2;
*n2 = *n1;
*n1 = temp;
}
int main(int argc, char** argv) {
int arr[3];
for(int i = 0; i<3; i++)
{
printf("Input %d:", i+1);
scanf("%d", arr+i);
}
swap1(arr, arr+1, arr+2);
for( int i =1; i <=3; i++)
{
printf("After swap element %d - %d\n", i, arr[i] );
}
return (EXIT_SUCCESS);
}
Thank you in advance for your help.
for( int i =1; i <=3; i++)?? Array indices start at 0 and end at the size of the array - 1. Your program has undefined behavior. Any decent compiler (invoked properly) would warn you of this. Forgcc/clang, consider the options-Wall -Werror -Wextra -O2 -gAlso, always check the return value ofscanf. - costaparas