// 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 typeint
. The function is expecting the location in memory (ie, a pointer) of a value of typeint
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 pointernumber
is being dereferenced, that is theint
type value is being retrieved from the location “in memory”number
“points” to. This value is summed with1
, 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 be1
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 caseint
.
add1(&number);
- The function
add1
is called, and the and the&
“address-of” operator is used to generate a pointer tonumber
. Theadd1
function is not expecting anint
value but is expecting a pointer to an object of typeint
.
Sources:
- Effective C
- Stack Overflow