Question: I have a question which involves calling a function with 2 parameters of a pointer to a pointer

```
int main(void)
{ ...
int *ptrp = &p, *ptrq = &q;
int **ppp = &ptrp, **ppq  = &ptrq;
swap_ptr(ppp,ppq);/* &ptrp, &ptrq passed */ 
/* to swap_ptr() */
return 0;
}

void swap_ptr(int **ptrA,int **ptrB)...

```

We have to swap the values of ptrp and ptrq, so does that mean in the swap\_ptr function I just use \*ptrA and \*ptrB to swap them or is it some other pointer statement?

Thanks

Answer: 
It's the same concept as swapping anything:

```
void swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

```

In this case, you just happen to be swapping int\* instead of int:

```
void swap(int** a, int** b)
{
    int* tmp = *a;
    *a = *b;
    *b = tmp;
}

```
I'm kind of new with these algorithms/techniques but I've had came up with this function;

```
function swap(int *p1, int *p2) {
  *p1 = *p1 + *p2;
  *p2 = *p1 - *p2;
  *p1 = *p1 - *p2;
}

```

You can test this function like that;

```
int a = 10;
int b = 20;

printf("%d %d\n", a, b); // 10 20

swap(&a, &b);

printf("%d %d\n", a, b); // 20 10

```

---

Here's a 3-step explanation for better understanding; 

1. `*p1 = *p1 + *p2;`  

Add the values coming from **p1** *(\*p1=10)* and **p2** *(\*p2=20)* and store result on **p1** *(\*p1=30)*.
2. `*p2 = *p1 - *p2;`  

We know result of the addition, calculate the old value of **p1** by subtracting current value of **p2** *(current \*p2=20)* from value coming from **p1** *(\*p1=30)* and store result on **p2** *(calculated \*p2=10)*.
3. `*p1 = *p1 - *p2;`  

Since the value of **p1** *(\*p1=30)* did not change on step 2 and we still have the old value of **p1** on **p2** *(\*p2=10)*, we can divide **p2** into **p1** and store the result on **p1** *(calculated \*p1=20)*

So as you can see we swapped two `int`s **without defining any temporary variable** and making pass-by-reference function call.

The reason of pass-by-reference is to minimize usage of memory. Because every pass-by-value call allocates new variables on the memory (to be deleted by GC or not) depends on how much parameter you've passed to the function.