Sna*_*ape 4 c c++ memory swap pointers
what happens when we modify the swap function this way ? I know it doesn't work but what exactly is going on ? I'm not understanding what I actually did ?
#include <stdio.h>
void swap(int*, int*);
int main(){
int x=5,y=10;
swap(&x, &y);
printf("x:%d,y:%d\n",x,y);
return 0;
}
void swap(int *x, int *y){
int* temp;
temp=x;
x=y;
y=temp;
}
Run Code Online (Sandbox Code Playgroud)
In the function
void swap(int* x, int* y){
int* temp;
temp=x;
x=y;
y=temp;
}
Run Code Online (Sandbox Code Playgroud)
you just swap the pointer values for the two function arguments.
If you want to swap their values you need to implement it like
void swap(int* x, int* y){
int temp = *x; // retrive the value that x poitns to
*x = *y; // write the value y points to, to the memory location x points to
*y = temp; // write the value of tmp, to the memory location x points to
}
Run Code Online (Sandbox Code Playgroud)
that way the swap function swaps the value for the referenced memory locations.
void swap(int *x, int *y){
int* temp;
temp = x;
x = y;
y = temp;
}
Run Code Online (Sandbox Code Playgroud)
swap()需要两个指向int此处的指针,但在内部仅交换本地指针的值x和y- 它们指向的对象的地址。- 表示在结束swap()之前,它返回之前,x指向y已经指向的对象和y指向x已经指向的对象。
在对象x和y指向的调用者中没有影响。
如果要交换 whichx和y指向的对象的值,则需要这样定义swap():
void swap(int *x, int *y){
int temp;
temp = *x; // temp gets the int value of the int object x is pointing to.
*x = *y; // x gets the int value of the int object y is pointing to.
*y = temp; // y gets the int value of temp (formerly x).
}
Run Code Online (Sandbox Code Playgroud)
示例程序(在线示例):
#include <stdio.h>
void swap(int *x, int *y){
int temp;
temp = *x; // temp gets the int value of the int object x is pointing to.
*x = *y; // x gets the int value y of the int object y is pointing to.
*y = temp; // y gets the int value of temp (formerly x).
}
int main (void)
{
int a = 1, b = 2;
printf("Before the swap() function:\n");
printf("a = %d b = %d\n\n",a,b);
swap(&a,&b);
printf("After the swap() function:\n");
printf("a = %d b = %d",a,b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Before the swap() function:
a = 1 b = 2
After the swap() function:
a = 2 b = 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |