cpointersaddress-operator

What is the difference between mymethod(i) and mymethod(&i) in C?


I was wondering what the difference in is between calling a method like :

int x;
mymethod(x); 

and

mymethod(&x);

Solution

  • Because C always does call-by-value, if you want the function to be able to change the x inside the function itself, you have to pass the address of x.

    mymethod(x);
    

    will pass x, for example if x is 2, you could as well have written mymethod(2)

    mymethod(&x)
    

    will pass the address to x. Now the method can change the value stored at that address, so after the function is completed, the actual value of x might have been changed.

    Now you can also declare a pointer:

    int* y; //y is now a pointer to a memory address
    y = &x; //y now points to the memory address of x;
    *y = 5; will set the "value found at the address y" to 5, thus will set x to 5;