Pointer-to-Array .

In this session i have discussed pointer to array in C++ .


An arrya is a constant pointer to first element of array . Array declaration as follows .

    int arr[10];
    

In the above code the arr is contant pointer to &arr[0] . Which is the first element of arr .

    int*ptr;
    int arr[10];
    ptr=arr;
    

In the above code we have declare a pointer of type int and an array of type int . the arr is constant pointer so we can assign the arr to ptr . This will assign the first element address to ptr . You can write *(ptr+2) this will print the third index value of array .


Example : Write a program that print the array value using pointer .

    #include<iostream>
    using namespace std;  
    int main()
    {  
          int*ptr;
          int i=0;
          int arr[]={10,20,30,40};
          ptr=arr;
          while(i<4)
          {
                cout<<"(p+"<<i<<")";
                cout<<" = "<<*ptr<<"\n";
                ptr++;
                i++;    
          }
          return 0;
    }
    
    OUTPUT : (p+0)=10
             (p+1)=20
             (p+2)=30
             (p+3)=40
    


Example : Write a program that sum the array using pointer .

    #include<iostream>
    using namespace std;  
    int main()
    {  
          int*ptr;
          int i=0;
          int sum=0;
          int arr[]={10,20,30,40};
          ptr=arr;
          while(i<4)
          {
                sum=sum+*(ptr);
                ptr++;
                i++;
          }
          cout<<"Sum : "<<sum;
          return 0;
    }
    
    OUTPUT : Sum : 100
    


Welcome to AndroidATPoint.

back image                     next image