简体   繁体   English

这两种指针方法之间的区别

[英]Difference between these two pointer methods

Decode1: 解码1:

void decode1(int *xp, int *yp, int *zp){
 int x = *xp;
 int y = *yp; 
 int z = *zp;
 xp = &z;
 yp = &x;
 zp = &y;
}

Decode2: 解码2:

 void decode2(int *xp, int *yp, int *zp){
 int x = *xp;
 int y = *yp; 
 int z = *zp;
 *xp = z;
 *yp = x;
 *zp = y;
}

Decode1 will change the pointer to address of the z, x, and y. Decode1会将指针更改为z,x和y的地址。 Decode2 will instead change the value at the address of the pointer. Decode2将改为更改指针地址处的值。 Are these two methods interchangeable? 这两种方法可以互换吗? Are there situations where one is more correct than the other? 是否存在其中一种比另一种更正确的情况?

Decode2 is correct procedure. Decode2是正确的过程。 In Decode1, after end of the call stack, the address you have assigned in xp,yp,zp will be vanished. 在Decode1中,在调用堆栈结束后,您在xp,yp,zp中分配的地址将消失。

No they are not interchangeable and they don't do the same thing. 不,它们是不可互换的,并且它们不会做相同的事情。

decode1 will not work and decode2 will work (assuming that you want to swap the variables). decode1将不起作用,而decode2将起作用(假设您要交换变量)。

The decode1 function places x , y and z on the stack and these variables only exist while the function is executing. decode1函数将xyz放在堆栈上,并且这些变量仅在函数执行时存在 The moment it returns these variables no longer point to valid memory. 它返回这些变量的时刻不再指向有效内存。 Also, the pointers xp , yp and zp are copies of the pointers that were passed to the function so you won't be modifying the original pointers (hence altering them in the function does absolutely nothing). 同样,指针xpypzp是传递给该函数的指针的副本,因此您不会修改原始指针(因此在函数中对其进行更改绝对不会执行任何操作)。

The decode2 function will work as expected. decode2函数将按预期方式工作。

decode1 attempts to returns pointers to local variables but in the end simply does nothing. decode1尝试返回指向局部变量的指针,但最后根本不执行任何操作。 Use decode2 . 使用decode2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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