C++ pointer to array

You can create a pointer to point an array. When a pointer points to array, it points to the first item of array.

#include <iostream>
#include <conio.h>
#include <cmath>
using namespace std;

int main(){
   int *p;
   int arr[]={3,4,5,23,11,5,9};
   int size=sizeof(arr)/sizeof(int);
   p=arr;
   cout<<*p<<endl;//output first element of the array
   //outful all array elements
   for(int i=0;i<size;i++)
    cout<<*(p+i)<<"\t";
   getch();
   return 0;
}

I found pointer to array useful when we want a function to return any array as you see in the example code below.

#include <iostream>
#include <conio.h>
#include <cmath>
using namespace std;
int size;
int *sortarr(int list[]){
   for(int i=0;i<size;i++){
        int smallest=i;
        for(int j=i+1;j<size;j++)
             if(list[j]<list[smallest])
               smallest=j;
        int temp=list[smallest];
        list[smallest]=list[i];
        list[i]=temp;
        }
        return list;
}
int main(){
   int *rp;
   int arr[]={3,4,5,23,11,5,9};
   size=sizeof(arr)/sizeof(int);
   rp=sortarr(arr);
   for(int i=0;i<size;i++)
    cout<<*(rp+i)<<"\t";
   getch();
   return 0;
}

Posted by: Dara | post date: 01-26-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.