+ 2
how can i return an array from a function
i know we need to return pointer but my implementation failed. plz write/give a code which returns an array
5 Answers
+ 4
Try this:
int* increment(int arr[], int size, int incr=0)
// Function to return an incremented
// array, by factor of incr.
{
int* farr = new int[size];
for(int i=0;i<size;i++)
{ farr[i] = arr[i]+incr; }
return farr;
}
int main()
{
int arr[10]; int* res = new int[10];
//Random size of 10.
for(int i=0;i<10;i++) { cin>>arr[i]; }
res = increment(arr,10,3);
//Increment each element by 3.
for(int i=0;i<10;i++) { cout<<res[i]<<" "; }
}
+ 4
@shobhit
The [] operator is also overloaded for pointers.
After all, arrays and pointers both are technically the same thing. They are interconnected.
+ 3
@luka myarr is a pointer isn't it then how can we use its index