The way there can be an array of ints or an array of floats, similarly there can be an array of pointers. Since a pointer variable always contains an address, an array of pointers would be nothing but a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses. All rules that apply to an ordinary array apply to the array of pointers as well. I think a program would clarify the concept.
main( )
{
int *arr[4] ; /* array of integer pointers */
main( )
{
int *arr[4] ; /* array of integer pointers */
int i = 31, j = 5, k = 19, l = 71, m ;
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ )
printf ( "%d ", * ( arr[m] ) ) ;
}
below Figure shows the contents and the arrangement of the array of pointers in memory. As you can observe, arr contains addresses of isolated int variables i, j, k and l. The for loop in the program picks up the addresses present in arr and prints the values present at these addresses.
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ )
printf ( "%d ", * ( arr[m] ) ) ;
}
below Figure shows the contents and the arrangement of the array of pointers in memory. As you can observe, arr contains addresses of isolated int variables i, j, k and l. The for loop in the program picks up the addresses present in arr and prints the values present at these addresses.
An array of pointers can even contain the addresses of other arrays. The following program would justify this.
main( )
{
static int a[ ] = { 0, 1, 2, 3, 4 } ;
int *p[ ] = { a, a + 1, a + 2, a + 3, a + 4 } ;
printf ( "\n%u %u %d", p, *p, * ( *p ) ) ;
}
I would leave it for you to figure out the output of this program.
printf ( "\n%u %u %d", p, *p, * ( *p ) ) ;
}
I would leave it for you to figure out the output of this program.
No comments:
Post a Comment