如何在函数中切换指针?

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编程语言在函数中切换指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1970384/

10-09 09:02