c++ - C语言中函数中的switch指针

标签 c++ c pointers function swap

如何在函数中切换指针?

void ChangePointers(int *p_intP1, int *p_intP2); 

int main() {

int i = 100,  j = 500;
int *intP1, *intP2; /* pointers */
intP1 = &i;
intP2 = &j;
printf("%d\n", *intP1); /* prints 100 (i) */
printf("%d\n", *intP2); /* prints 500 (j) */
ChangePointers(intP1, intP2);


printf("%d\n", *intP1); /* still prints  100, would like it swapped by now */
printf("%d\n", *intP2); /* still prints  500 would like it swapped by now */
}/* end main */

void ChangePointers(int *p_intP1, int *p_intP2) {
int *l_intP3; /* local for swap */
l_intP3 = p_intP2;
p_intP2 = p_intP1;
p_intP1= l_intP3;
}

最佳答案

在 C 中,参数总是按值传递。尽管您正在更改被调用函数内的指针变量的值,但更改不会反射(reflect)回调用函数。尝试这样做:

void ChangePointers(int **p_intP1, int **p_intP2); /*Prototype*/

void ChangePointers(int **p_intP1, int **p_intP2) /*Definition*/
{
    int *l_intP3; /* local for swap */
    l_intP3 = *p_intP2;
    *p_intP2 = *p_intP1;
    *p_intP1= l_intP3;
}

来自 main() 的相应调用应该是:

ChangePointers(&intP1, &intP2);/*Passing in the address of the pointers instead of their values*/

关于c++ - C语言中函数中的switch指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1970384/

相关文章:

c - 使用 vector 名称作为指针

c++ - 使用多态性重载 << 运算符

c++ - 错误: ‘void*’ is not a pointer-to-object type

c++ - 为什么我需要像临时构造这样的复合文字来初始化我的 std::array 成员?

c++ - 在 C++ 备选方案中检查空字符串

c - Linux、C语言中是否可以不使用任何系统调用来监视内存?

postgresql自定义函数的便利性VS plpgsql

c++ - float 数组对齐错误

c++ - "Inverse SFINAE"避免模棱两可的过载

c - C 中的匿名结构