int i; // An integer variable
int a[10]; // An integer array
int *p; // A reference variable to an int variable
// p can contain an address of an int variable
|
int i; // An integer variable
int a[10]; // An integer array
|
Illustrated:
|
Notice that:
|
int *p;
p = &i;
*p will access i
p = &a[0];
*p will access a[0]
p = &a[1];
*p will access a[1]
|
|
|
Comment:
|
|
Example C progra:
int main(int argc, char *argv[])
{
int a[10];
int *p;
p = &a[0]; // p points to variable a[0]
printf("p = %u, &a[%d] = %u\n", p, 0, &a[0] );
printf("p + 1 = %u, &a[%d] = %u\n", p+1, 1, &a[1] );
printf("p + 2 = %u, &a[%d] = %u\n", p+2, 2, &a[2] );
printf("p + 3 = %u, &a[%d] = %u\n", p+3, 3, &a[3] );
}
|
Output of C program:
p = 4290769444, &a[0] = 4290769444 (increased by 4 !!!) p + 1 = 4290769448, &a[1] = 4290769448 p + 2 = 4290769452, &a[2] = 4290769452 p + 3 = 4290769456, &a[3] = 4290769456 |
How to run the program:
|
|
In other words:
If p points to a[0] then:
p + 1 = &a[0] + 4 = the address of the array element a[1] !!
p + 2 = &a[0] + 8 = the address of the array element a[2] !!
|
|
|
In other words:
If p points to a[5] then:
p - 1 = &a[5] - 4 = the address of the array element a[4] !!
p - 2 = &a[5] - 8 = the address of the array element a[3] !!
|
|