C: Pointers
In C, there are variables that contain the addresses of other variables. Such variables are known as pointers.
An address of a variable can be accessed by the unary operator &
, generally known as the "address-of" operator. So, &n
gives the address of the variable n
and the printf()
statement below will print it
int n = 1;
printf("%p", &n);
The address will be some value like 0x7ffcb297060c
.
We have another unary operator *
, known as the deferencing operator. When applied to a pointer, it gives the value of the variable whose memory it holds. We explain it here: &n
gives the "address of n", therefore, *(&n)
gives the "value at address of n," which is n
itself. The below printf()
statement will print 1, which is the value of n
int n = 1;
printf("%d", *(&n));
Declaring a Pointer
A pointer variable has a type associated with it. A pointer variable p
pointing to int
is declared as
int *p;
It conveys that it will only hold the address of a variable of type int
. It is then known as an integer pointer. The declaration is also an inkling that the expression *p
has an integer value.
Let us declare a variable n
of type int
and initialize it to some value, say 1. The integer pointer p
is assigned the address of n
. The first print()
statement prints the address of n
, which is some value like 0x7fff6aee5fe4
int n = 1;
int *p;
p = &n;
printf("%p", p);
printf("%d", *p);
The last print()
statement prints the value of n
itself.
Pointer to Pointer
We have seen pointers to int
. We can have pointers to char
and pointers to float
. We can also have pointers to pointers.
Consider the integer pointer m
, to which is assigned the address of n
. The next integer pointer p
is declared to hold the address of another pointer, and hence the double asterisk **p
. The pointer variable p
is assigned the address of the integer pointer m
int n = 1;
int *m;
int **p;
m = &n;
p = &m;
printf("%p", p);
The printf()
statement prints the address of the integer pointer m
.