How do you switch pointers in a function?
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;
}
In C, parameters are always passed by values. Although you are changing the values of the pointer variables inside the called function the changes are not reflected back to the calling function. Try doing this:
Corresponding call from main() should be: