// add1.c

#include <stdio.h>
#include <stdlib.h>

void add1(int *number)
{
	*number = *number + 1;
}

int main(void)
{
	int number = 0;

	add1(&number);

	if (printf("%d\n", number) < 0)
	{
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

This example expands upon information provided in a previous tutorial, how a “Hello World” program is written in C.

Details

void add1(int *number)

  • The parameter of the add1 function is a pointer to an object of type int. The function is expecting the location in memory (ie, a pointer) of a value of type int to be used as the only argument when called.

*number = *number + 1;

  • In this statement, the expression on the right is first evaluated. *number indicates the pointer number is being dereferenced, that is the int type value is being retrieved from the location “in memory” number “points” to. This value is summed with 1, then assigned.
    • Dereferencing, from the linked Stack Overflow article, is described as: “When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.”
  • On the left, the pointer is derefenced, so it is writing directly to the memory that the pointer number “points” to.
  • After this statement is completed, any variable whose value comes from the memory location for number is now changed, to be 1 greater than it was previously.

int number = 0;

  • The variable to have it’s value changed by another function is initialised, and assigned a value 0. The type of the variable should be the same as the type expected by the function parameter receiving the reference to the variable, in this case int.

add1(&number);

  • The function add1 is called, and the and the & “address-of” operator is used to generate a pointer to number. The add1 function is not expecting an int value but is expecting a pointer to an object of type int.

Sources: