Results 1 to 6 of 6

Thread: reference parameter in c

  1. #1
    Join Date
    May 2013
    Beans
    27

    reference parameter in c

    how to pass a reference parameter to function?!?
    i tested this code:
    Code:
    void func ( int * var)
    {
          int x=3;
          var =x;
    }
    int main()
    {
         int a=4;
         func( & a);
         printf("%d",a);
         return 0;
    }
    output isn't 3.
    Last edited by lisati; May 13th, 2013 at 09:26 PM. Reason: Added [code] and [/code] to aid readbility

  2. #2
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,664
    Distro
    Ubuntu 13.10 Saucy Salamander

    Re: reference parameter in c

    Code:
    void func ( int * var)
    {
        int x=3;
        var =x;
    }
    The parameter is a pointer to the value you want to change, but you are assigning a value to the pointer itself, instead of to the value that the pointer points to.
    Please create new threads for new questions.
    Please wrap code in code tags using the '#' button or enter it in your post like this: [code]...[/code].

  3. #3
    Join Date
    May 2013
    Beans
    27

    Re: reference parameter in c

    yeah, but i test this instruction:
    *var =x;
    but not correct.

  4. #4
    Join Date
    Jul 2009
    Location
    Italy
    Beans
    68
    Distro
    Ubuntu 13.04 Raring Ringtail

    Re: reference parameter in c

    This works ok for me
    Code:
    #include <stdio.h>
     
    void func ( int *var){
      int x = 3;
      *var = x;
    }
    
    int main(){
      int a=4;
      func(&a);
      printf("%d\n",a);
      return 0;
    }
    I get 3

  5. #5
    Join Date
    May 2013
    Beans
    27

    Re: reference parameter in c

    i am runing this code, but when arrive to this instruction ( *var = x; ) , program stop and say this:
    Segmentation fault (core dumped)

  6. #6
    Join Date
    Jul 2009
    Location
    Italy
    Beans
    68
    Distro
    Ubuntu 13.04 Raring Ringtail

    Re: reference parameter in c

    It's strange, I've just pasted the code I posted before in a file, saved and compiled it with

    Code:
    cc file_name.c -o executable_name
    and it works. The gcc version installed on my pc is 4.7.3

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •