call by reference program

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 ...

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    1

    call by reference program

    I want to better understand the purpose of Call by Reference in C language

    Please provide me some examples with explanation.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    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.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    21
    Quote Originally Posted by quzah View Post
    C doesn't have references. Nothing in C is passed by reference. Everything is a value.


    Quzah.
    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.).

    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);
    }
    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.

    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Confused with call by reference...
    By jawwadalam in forum C++ Programming
    Replies: 4
    Last Post: 11-17-2002, 02:07 AM
  2. Call-by-value Vs. Call-by-reference
    By Wiz_Nil in forum C++ Programming
    Replies: 3
    Last Post: 02-20-2002, 08:06 AM
  3. Call-by-reference
    By theweirdo in forum C Programming
    Replies: 4
    Last Post: 01-30-2002, 12:27 PM
  4. call by reference
    By Jackie in forum C Programming
    Replies: 3
    Last Post: 10-29-2001, 05:46 AM
  5. call by reference and a call by value
    By IceCold in forum C Programming
    Replies: 4
    Last Post: 09-08-2001, 05:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21