The & operator, the address-of operator, the ampersand operator
The punctuation character &,
often pronounced as the address-of operator,
is used to find a variable's address.
For example, we'd pronounce this as:
int total;
.... &total ....
|
"the address of total",
and if the integer variable total was located at memory address
10,000 then the value of &total would be 10,000.
We can now introduce a variable named p,
which is a pointer to an integer
(pedantically, p is a variable used to store the address of a
memory location that we expect to hold an integer value).
int total;
int *p ;
p = &total ;
|
If the integer variable total was located at memory address
10,000 then the value of p would be 10,000.
If necessary (though rarely),
we can print out the address of a variable,
or the value of a pointer,
by first casting it to something we can print,
such as an unsigned integer,
or to an "generic" pointer:
int total;
int *p = &total ;
printf("address of variable is: %lu\n", (unsigned long)&total );
printf(" value of pointer p is: %lu\n", (unsigned long)p );
printf(" value of pointer p is: %p\n", (void *)p );
|
CITS2002 Systems Programming, Lecture 11, p3, 26th August 2024.
|