gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:01:15 26 4
gpt4 key购买 nike

如何在函数中切换指针?

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com