← The C Language
Lesson 28 of 77 · 10 XP
Passing by reference with a pointer
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
If a function has to change a variable of the calling code, it's given the address:
void increment(int *p)
{
(*p)++; // change the value at the address
}
int a = 5;
increment(&a);
printf("%d\n", a); // 6
Strictly speaking, everything in C is passed by value. Here the address is passed by value, and through it the function reaches the original. That's exactly how scanf("%d", &x) works.
The parentheses in (*p)++ matter: *p++ means "move the pointer, then dereference".
The same trick lets you "return" several values:
void divmod(int a, int b, int *q, int *r)
{
*q = a / b;
*r = a % b;
}
Task. Write the classic void swap(int *a, int *b) from K&R, which swaps the values of two variables. In main, read two numbers, call swap and print them.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.