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 :

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 more from one element to another. The relationship between P and X is shown below :

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(P+3) gives the value of X[3]. The pointer accessing method is more faster than array indexing.

POINTERS AND FUNCTIONS

When an array is passed to a function as an argument, only the address of the first element of the array is passed, but not the actual values of the array elements. The function uses this address for manipulating the array elements. Similarly, we can pass the address of a variable as an argument to a function in the normal fashion. When we pass addresses to a function, the parameters receiving the addresses should be pointers. The process of calling function using pointers to pass the address of variable is known as call by reference. The function which is called by reference can change the value of the variable used in the call. eg.

When the function change is called, the address of the variable X, not its value, is passed into the function change ( ). Inside change ( ), the variable P is declared as a pointer and therefore P is the address of the variable X. The statement,

means add 10 to the value stored at address P. Since P represents the address of X, the value of X is changed from 50. Therefore, the output of the program will be 50 not 40. These, call by reference provides a mechanism by which the function can change the stored values in the calling function.

Share
Tweet
Share
Pin
+1