Pointers
Pointers
- Every variable has a memory address. e.g.,
int i =3, j = 5;
double k = 6.9;
may store the variables as:
Variable | Address | Value |
---|
i | 0xF7FFF554 | 3 |
j | 0xF7FFF550 | 5 |
k | 0xF7FFF548 | 6.9 |
- In C and C++ you have access to the value and the address of
a variable
- Special variables called pointers may be defined to store
addresses of other variables. e.g.,
int* p ; // Declares a pointer that will store the address of an
integer variable
- The address of a variable is determined using the & operator.
e.g., in the above example,
i = 3 but &i = 0xF7FFF554
j = 5 but &j = 0xF7FFF550
k = 6.9 but &k = 0xF7FFF548
- The dereferencing operation - pointing to the value contained
in an address is denoted by *
Therefore *(&i) is equivalent to i
- Using the previous definitions of i, j, k, the following is
valid:
int* p = &i;
and its effect is:
Variable | Address | Value |
---|
i | 0xF7FFF554 | 3 |
j | 0xF7FFF550 | 5 |
k | 0xF7FFF548 | 6.9 |
p | 0xF7FFF544 | 0xF7FFF554 |
- The following statement:
*p = 40;
changes the above table to:
Variable | Address | Value |
---|
i | 0xF7FFF554 | 40 |
j | 0xF7FFF550 | 5 |
k | 0xF7FFF548 | 6.9 |
p | 0xF7FFF544 | 0xF7FFF554 |
- Any variable that appears on the left hand side of an assignment
statement is called an lvalue
i, *p and *&i are valid lvalues
&i is not a valid lvalue
Back to Previous Page
Document:
Local Date:
Last Modified On: