Pointers in C
C supports pointers, allowing you to pass references to values and records within your program.
In this example, we demonstrate how pointers work in contrast to values using two functions: zeroval
and zeroptr
.
The zeroval
function takes an int
parameter, so arguments are passed to it by value. This means zeroval
receives a copy of the value, distinct from the one in the calling function.
On the other hand, zeroptr
takes an int*
parameter, which is a pointer to an integer. Inside the function, *iptr
dereferences the pointer, allowing us to modify the value at the memory address it points to.
In the main
function, we create an integer i
and demonstrate the difference between passing by value and passing by reference:
- We first print the initial value of
i
. - We call
zeroval(i)
, which doesn’t change the value ofi
inmain
. - We then call
zeroptr(&i)
, passing the address ofi
. This changes the value ofi
inmain
because it has a reference to the memory address of that variable. - Finally, we print the memory address of
i
using the%p
format specifier.
To compile and run this C program:
Note that the actual memory address (pointer value) will likely be different on your system.
This example demonstrates the fundamental concept of pointers in C, which allows for efficient manipulation of data by reference.