Sunday, 20 May 2012

array with memory

Array stores in contiguous memory  where each element in array have equal size of  memory because it is collection of similar type of data.

If we want to know about memory location of any element, it is find out on the basis of base (starting) element of array. 

Situation 1

This situation is like train where we can consider it's engine as base element and can reach any compartment of it. Because we know starting of this chain. 

Situation 2

We have a street on which each house is equal in size. Address of first house is A-1 and we want to reach A-4 . So how it is possible. 
first we need to reach at A-1 and then  A-2 .....A-4.




Conclusion

  Compiler never remember all elements address. It know only starting address of array element and reach  or access any element on the basis of it.

                              size=2              size=2                size=2              size=2       
                         [element 1]--->[element 2]--->[element 3]--->[element 4]

                          Address 1         Address 2         Address 3        Address 4

If we assume  starting address of  element 1 is 1000 then what's about address 2. can we assume. It's simple like reaching A-1 to A-2 . We simply add size of element 1 to starting address. Means 
 
Address of element 1  is  1004                   = Address 1
Address of element 2  is  1000+2 = 1004 = Address 2
Address of element 3  is  1004+2 = 1006 = Address 3
Address of element 4  is  1006+2 = 1008 = Address 4

Result : compiler reaches to new element on the basis of base element. It simple adds size of element to base address. Size of element is vary and based on data type. that is


Character   1  byte
Integer        2  byte
Float             4  byte  



















No comments:

Post a Comment