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:
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;
}
Corresponding call from main() should be:
ChangePointers(&intP1, &intP2);/*Passing in the address of the pointers instead of their values*/
You need a pointer to the pointer.
ChangePointers(&intP1, &intP2);
void ChangePointers(int **p_intP1, int **p_intP2) {
int *l_intP3;
l_intP3 = *p_intP2;
*p_intP2 = *p_intP1;
*p_intP1 = l_intP3;
}
Change the signature to take a pointer to a pointer.
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;
}
Or, if you want the calling code to look the same, resembling C++ references, use a macro.
void ChangePointersImpl(int **p_intP1, int **p_intP2) {
int *l_intP3; /* local for swap */
l_intP3 = *p_intP2;
*p_intP2 = *p_intP1;
*p_intP1= l_intP3;
}
#define ChangePointers(a,b) ChangePointersImpl(&a, &b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With