0
votes

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.

1
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. For gcc/clang, consider the options -Wall -Werror -Wextra -O2 -g Also, always check the return value of scanf. - costaparas
That was my error, thanks. Finally getting the expect output. I'm using netbeans as IDE but I didn't got any warning, - Luís Oliveira
@costaparas Any decent compiler would complain, withouth the optimization switch there are no warnings, checked on both the latest version of gcc and clang. - alex01011
@alex01011 yes, with optimization turned on (at least O1), you get loop optimizations, which will throw the warning. OP should be compiling with optimization (preferably O2+). - costaparas

1 Answers

1
votes

Your problem is here:

for( int i =1; i <=3; i++)
{
    printf("After swap element %d - %d\n", i, arr[i] );
}

this code should be:

for( int i =0; i <3; i++)
{
    printf("After swap element %d - %d\n", i+1, arr[i] );
}

Remember that on C arrays start at 0.