Passing a Pointer

On the previous page we learned that all functions in C accept their parameters by value, which means they only have copies of the values: a function void f(int x), when called as f(a), cannot change the value of a in the calling function.

But if we really want to make it possible, there is an easy way to do it: instead of passing an int value, why don't we pass a pointer to that value? In that case the function will not change its parameter (the address stored in the pointer will remain the same), but the function will instead dereference the pointer and change the value it points to.

Look at this example:

#include <stdio.h>

void f(int *p) {
	(*p)++; /* we need parentheses around *p here, otherwise it won't do what you expect */
}

int main() {
	int a = 5;
	printf("before: %d\n", a);
	f(&a); /* passing address of variable a */
	printf("after: %d\n", a);
	return 0;
}

Try running the code and see that this time our function f was able to change the value of a, because instead of working on its copy, it now accepts an address stored in a pointer. It does not change its parameter, but it does change the value in memory at the address its parameter points to.

Remember our read_int function? Here is it, for your reference:

int read_int() {
	int result = 0;
	int c;

	while (isdigit(c = getchar())) {
		result = result * 10 + (c - '0');
	}

	return result;
}

Let's change it so it reads a value into a variable we pass as a parameter. Since it cannot change its parameter directly, we will need to pass a pointer! Since the result will be now stored in the parameter, the function can now return void:

void read_int(int *p) {
	...
}

Do you want to try writing it? Just as before, to test your code, I'll ask you to print the number it read from standard input, incremented by one:

#include <ctype.h>
#include <stdio.h>

void read_int(int *p) {
	/* your code here! */
}

int main() {
	int value;

	read_int(&value); /* take an address! */
	printf("%d\n", value + 1); /* print value plus one */

	return 0;
}

Did you make it work?