简体   繁体   中英

How can I fix the swapBack function to get the result I intended?

I am trying to implement a swap back function that will swap the values back to the original position. This is the instruction I have to do accordingly:

Implement a second swapping function, swapBack(int v[2]), that takes the vector v = [x, y] as an input and swaps its entries. Includes the new function into the program above to swap back the values of x and y.

#include <stdio.h>

void swap(int *pX, int * pY){
    int temp = *pX;
    *pX = *pY;
    *pY = temp;

}

void swapBack(int x, int y){
    swap(&x,&y);
}

int main() {
int x = 10;
int y = 5;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y);
swapBack(&x, &y);
printf("x = %d, y = %d\n", x, y);
return x + y;
}

However, both printf produce the same results and I am not sure how to fix it? thanks

You're defining swapBack wrong. It's supposed to take an array (which decays to a pointer) of two integers.

This should be about what you want:

void swapBack(int v[2])
{
    int temp = v[0];
    v[0] = v[1];
    v[1] = temp;
}

A program to test this:

#include <stdio.h>

void swapBack(int v[2])
{
    int temp = v[0];
    v[0] = v[1];
    v[1] = temp;
}

int main(void)
{
    int v[2] = {10, 5};

    printf("v[0] = %d, v[1] = %d\n", v[0], v[1]);
    swapBack(v);
    printf("v[0] = %d, v[1] = %d\n", v[0], v[1]);
    printf("v[0] + v[1] = %d\n", v[0] + v[1]);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM