[英]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.我正在尝试实现交换回 function,它将值交换回原始 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.实现第二个交换 function, swapBack(int v[2]),它将向量 v = [x, y] 作为输入并交换其条目。 Includes the new function into the program above to swap back the values of x and y.
在上面的程序中包含新的 function 以交换 x 和 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?但是,两个
printf
产生相同的结果,我不知道如何解决它? thanks谢谢
You're defining swapBack
wrong.您定义
swapBack
错误。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.