Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch pointers in a function in the C programming language

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;
}
like image 356
Chris_45 Avatar asked Dec 28 '09 16:12

Chris_45


3 Answers

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*/
like image 199
Prasoon Saurav Avatar answered Sep 21 '22 07:09

Prasoon Saurav


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;
}
like image 22
Mak Kolybabi Avatar answered Sep 19 '22 07:09

Mak Kolybabi


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)
like image 44
Drew Dormann Avatar answered Sep 19 '22 07:09

Drew Dormann