Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing addresses to functions in C

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?

like image 831
Amit Avatar asked Dec 13 '22 14:12

Amit


1 Answers

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.

like image 97
mmx Avatar answered Dec 20 '22 18:12

mmx