সোমবার, ১৮ অক্টোবর, ২০১০

35. Introduction to Pointer and Arrays

Pointer and arrays:
1. Array elements are always stored in contiguous memory location.
2. A pointer when incremental always pointer to an immediately next location of its type.
Suppose we have an array,
int mamun[ ]={3,4,5,6};
Suppose the elements are located in memory as
Elements:               3        4           5           6
Memory location: 1000   1002      1004      1005
Here is program that prints out the memory location in which the elements of this array are stored.

main( )
{
   int mamun[ ]={3,4,5,6};
   int i=0,*p;
   p=mamun;   /*Because the array name is a base address of first elemnt of the array. We cam also write it p=mamunb[0]*/
     while (i<=4)
 {
    printf(" \n Address = %u",&mamun[i]);
    printf("\n Element = %d", *p);
    i++;
    p++;
 }
}
output:
address             elements
1000                  3
1002                  4
1004                  5
1006                  6

in this program, to begin with  we have collected the base address of the array(address of 0th  element) in the variable p using the statement,
p=mamun; /*assigns address 1000to p*/.
When we are inside the loop for the first time p contains the address 1000,and the value at this address is 24.
These continue till the last element of the array has bee n printed.

A word of caution! D o not attempt the following operations on pointer ... they would never work out.
1. Addition of two pointers.
2. Multiplying a pointer with a number.
3. Dividing a pointer with a number. 

written by mamun

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন