Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass By Reference Using C

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;
}
like image 740
Fred Hotchkin Avatar asked Sep 22 '26 04:09

Fred Hotchkin


1 Answers

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;
like image 70
bobbymcr Avatar answered Sep 25 '26 00:09

bobbymcr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!