Tuesday, 29 November 2011



From bookish point of view...an array is a collection of homogeneous data, by homogeneous we mean dat the data vil be of same data type,may it be int or char or float.
int arr[10]..is an array of data type integer with 10 variables occupying size of 40 bytes.
Dis vil be same as defining int a0,a1,a.....a9
But the difference is dat v can now access dem easily through 1 name.
for eg: if v want to access 2nd element we will do like arr[1] ,5th element arr[4] and so on.
Remember: array-name[index]
array-name can be anythng and index starts from 0 and not 1.
an array of 5 elements: int arr[5]
defining simple variables : arr1 arr2 arr3 arr4 arr5
using array arr[0] arr[1] arr[2] arr[3] arr[4]
notice the indices
Hope u get it..!!
You can treat them just like normal variables but accessing them through array style.
Remember: Arrays are allocated in memory contiguously.
for eg: in ram arr[0],arr[1],arr[2] will be adjuacent to each other
like address of arr[0] is 1000,address[1] is 1004 and so on...!!
Now internally arrays are nothing more than "CONSTANT POINTERS".
For eg: u declare int arr[10];
then arr is only the address of arr[0] and it vil always point to that location only
For eg : int arr[5]; lets assume arr is pointing to 1000
So what happens when u require arr[3].
arr + index*sizeof(datatype) this formula is used
1000 + 3*4 //sizeof(int) is 4
which gives 1012 this vil be the address of arr[3].
Remember when i told u that arrays are allocated contigously in memory.This is the main importance . if they are not allocated contiguously then this scheme would fail.
Since the compiler just multiplies d index with the size of data type and adds it to base address...u vil be surprised to knw that u can also use array like
3[arr]..this vil be same as arr[3].

and remember that arrays are like constant pointers internally
you cannot assign an array to another variable once its been defined.
and due to the way that arrays are implemented internally they hav O(c) access time..
which means constant access time.
for further experience actually code the arrays for first hand experience.

No comments:

Post a Comment