I understand that when you pass by reference through a function in C, the parameters of the function take in the address of the pointer that will be modified. I am extremley boggled on why this example of pass by reference is not working. Can anyone point me in the right direction....
This should output a swap but when i compile the swap does not occur why is this pass by reference not working?
#include <stdio.h>
void swapnum(int *i, int *j) {
int temp = i;
i = j;
j = temp;
}
int main(void) {
int a = 10;
int b = 20;
swapnum(&a, &b);
printf("A is %d and B is %d\n", a, b);
getchar();
getchar();
return 0;
}
You forgot to dereference your pointers inside the function. Thus you end up reassigning the local pointer values rather than changing the actual value being pointed to and it has no effect.
So, use the * dereference operator:
int temp = *i;
*i = *j;
*j = temp;
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