+ 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

20th Oct 2017, 1:39 PM
shobhit
shobhit - avatar
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]<<" "; } }
20th Oct 2017, 3:06 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
@shobhit The [] operator is also overloaded for pointers. After all, arrays and pointers both are technically the same thing. They are interconnected.
21st Oct 2017, 3:40 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
@luka myarr is a pointer isn't it then how can we use its index
21st Oct 2017, 2:43 PM
shobhit
shobhit - avatar