C Language / Lesson 2 |
Back to top or to Previous Page or to Next Page |
Understanding Pointers and Addresses
When the finger points at the moon, the
idiot looks at the finger [Confucius]
The address operator
The address of a block of memory or a variable in memory is important to very powerful languages like C (in time you will realize the reasons why). Variables or expressions which refer to a block of memory by default return their address in C. On the contrary those variables containing one single value -called scalars - or elementary expressions referencing one single value by default return the value What if we want to have the address of a scalar ? Herein we introduce the address operator . It is the character & (ampersand) preceding an expression. Be careful :
x = &a | This is an address operator |
y = k & m | This is not an address operator |
Example : | |||||||||||||||||||||
| |||||||||||||||||||||
|
Examples
long *plng ;
char *current_message ;
int *n[12] ; // This is an aggregate (array) of 12 pointers and not a pointer to an aggregate
char msg[ ]= "Sample message" ; // this isn't a pointer - it is a string (character aggregate)
char *p = msg ; // This pointer is initialized to the address of the previous string
In the previous example the expression msg represents the address of
variable msg because, as explained earlier, msg is a block of memory containing
more than one values .
Note
: In C a string is not one single value but a composite variable (consisting
of more than one values) - every character in the string is a value and thus
the string is an aggregate of characters.
char max_files ; // This is only a one byte variable -a scalar character variable
char *p = &max_files ; // This pointer is initialized to the address of max_files
Note
: This time max_files is one single value and if we didn't use the address opearator,
the value of max_files would initialize the pointer and not the address.
The following example attempts to describe this situation graphically .
Two variables are defined :
int x and int *q
&x == 452 &q == 568
q is initialized (=&x) to the address of x , i.e. q == 452 (this is the value in q) The expression *q means the contents of the integer (since q is an int pointer) , which is stored at the address pointed by q i.e. the values of q. q==452 => at 452 is the 'home' of x and the contents are 14156. Therefore, the expression *q is == 14156. This adressing mode is called indirection because the access to 14156 was indirect through 452.