Pointers as Function Parameters

Call by Reference (1)

  • Problem: in C, parameters are passed by-copy* - callee see *copies of the caller’s values.

  • Question: how can I use a function to modify the caller’s value?

void f(int a)
{
    a = 42;
}

void main(void)
{
    int i = 1;

    f(i);
    /* i is still 1 */
}

Call by Reference (2)

Solution: pointer

void f(int *a)
{
    *a = 42;
}

void main(void)
{
    int i = 1;

    f(&i);
}
../../../../../../_images/call-by-reference.png

A sketch of that matter (made on a Wacom-tablet during one course)