I want to better understand the purpose of Call by Reference in C language
Please provide me some examples with explanation.
This is a discussion on call by reference program within the C Programming forums, part of the General Programming Boards category; I want to better understand the purpose of Call by Reference in C language Please provide me some examples with ...
I want to better understand the purpose of Call by Reference in C language
Please provide me some examples with explanation.
C doesn't have references. Nothing in C is passed by reference. Everything is a value.
Quzah.
Hope is the first step on the road to disappointment.
Too true. If you really need to pass something "by reference", then you should have a function that expects a pointer, rather than a value. (in the case of altering pointers, then you should expect a pointer to a pointer, etc. etc.).
The ampersand operator returns the address of the variable it is being applied to, essentially a pointer to that variable, and allows your fuction to change it. The asterisk (outside of declarations) derefrences the pointer, and returns the actual value therein, allowing you to edit it.Code:int someFunction(int *foo, char **bar){ *foo=someInt; *bar=someString; } int main (char** args, int argv){ int x=otherInt; char* y=otherString; somefunc(&x, &y); }
Thus, for any integer (say "x"):
x=the value you stored in x
&x=a pointer to that value
*x=gibberish, or a segfault, as your program tries to obtain the value of the memory address equivalent to that integer value
Hope that helps.