Pointer and Arrays


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:


The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the value of x is 1000, the location where x[0] is stored.That is,
                                    x = &x[0] = 1000
If we declare p  as an integre 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 as shown as:
                                    p = &x[0] (=1000)
                                    p+1 =  &x[1] (=1002)
                                    p+2 =  &x[2] (=1004)
                                    p+3 =  &x[3] (=1006)
                                    p+4 =  &x[4] (=1008)
You may notice that 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 * scale factor of int)
                        = 1000 + ( 3 * 2 ) = 1006

Previous                                                                                    Next


Powered by Blogger.