Sunday, November 16, 2008

Pointers and Arrays

POINTERS VS. ARRAY

When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element suppose we declare an array X as follows :

static int X [ 6 ] = { 1, 2, 3, 4, 5, 6 } ;

Suppose the base address of X is 1000 and assuming that each integer requires two bytes, the five elements will be stored as follows :

ELEMENTS x [0] x[1] x[2] x[3] x[4] x[5]

VALUE 1 2 3 4 5 6

Address 1000 1002 1004 1006 1008 1010

BASE ADDRESS

The name X is defined as a constant pointer pointing to the first clement,
x[0] and therefore the value of X is 1000, the location whose X[0] is stored. That is ;

X = & x[0] = 1000

If we declare P as an integer pointer, then we can make the pointer P to point to the array X by the following assignment :

P = X ;

This is equivalent to P = & X[0] ;

Now we can access every value of x using P++ to move from one element to another. The relationship between P and X is shown below :

P = & x[0] ( = 1000)

P+1 = & x[1] ( = 1002)

P+2 = & x[2] ( = 1004)

P+3 = & x[3] ( = 1006)

P+4 = & x[4] ( = 1008)

P+5 = & x[5] ( = 1010)

The address of an element is calculated using its index and the scale factor of the data type.

For instance,address of X[3] = base address + (3 x Scale factor of int)
= 1000 + (3 x 2) = 1006

When handling array, instead of using array indexing, we can use pointers to access array elements. Note that *(x+3) gives the value of X[3]. The pointer accessing method is more faster than array indexing.

No comments: