Passing addresses to functions in C

39,134

You should use *variable to refer to what a pointer points to:

*x = 5;
*y = 5;

What you are currently doing is to set the pointer to address 5. You may get away with crappy old compilers, but a good compiler will detect a type mismatch in assigning an int to an int* variable and will not let you do it without an explicit cast.

Share:
39,134
Amit
Author by

Amit

Please check out my website for more info.

Updated on July 06, 2020

Comments

  • Amit
    Amit almost 4 years

    I'm new to C and I have a function that calculates a few variables. But for now let's simplify things. What I want is to have a function that "returns" multiple variables. Though as I understand it, you can only return one variable in C. So I was told you can pass the address of a variable and do it that way. This is how far I got and I was wondering I could have a hand. I'm getting a fair bit of errors regarding C90 forbidden stuff etc. I'm almost positive it's my syntax.

    Say this is my main function:

    void func(int*, int*);
    
    int main()
    {
        int x, y;
        func(&x, &y);
    
        printf("Value of x is: %d\n", x);
        printf("Value of y is: %d\n", y);
    
        return 0;
    }
    
    void func(int* x, int* y)
    {
        x = 5;
        y = 5;
    }
    

    This is essentially the structure that I'm working with. Could anyone give me a hand here?

  • Amit
    Amit about 13 years
    One more question, what if in my function, I'm actually figuring out what a variable is from a file. Aka I have fscanf(file, "%d", &x), would it be fscanf(file, "%d", &*x); ?
  • Amit
    Amit about 13 years
    right of course, sorry I forgot that, I simply wrote the code in SO.
  • mmx
    mmx about 13 years
    Yes, it would be &*x. However, & is essentially the inverse of * in this context. So you can simply say x and it'll be the same thing. &x is definitely wrong though.
  • Amit
    Amit about 13 years
    Perfect. Thanks a lot for your help.
  • Mateen Ulhaq
    Mateen Ulhaq about 13 years
    It was originally void func(int *, int*);, but without code tags, that renders as: void func(int , int);.
  • Amit
    Amit about 13 years
    I got one last question, sorry! Is it good practice to work with variables like that, whereas you pass the address to the function and you change the value of the variable within the function itself, or is this looked down upon and shouldn't used? I figured that's probably one of the advantages of C, otherwise "returning" multiple variables would be a pain in the neck, wouldn't it?
  • mmx
    mmx about 13 years
    @Amit It's very common to use this style. But it shouldn't be used when a simple non-pointer variable would suffice. Additionally, in general, it's often a good idea to design your procedures to keep changes local to themselves rather than making global changes around the program. It eases debugging and improves maintainability.