I am new to C++ and trying to understand application of pointers and passing and returning arrays as argument.
In this code I have an array named ARR1 which is passed to function copy() as an argument this function prints ARR1 and creates ARR2(copy of ARR1) which is returned to main().
inside main() function i am trying to print arr2 but its giving wrong output.
HERE IS THE CODE:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int * copy(int *x, int y) {
int arr2[5] = {};
cout << "Printing ARR1 \n";
for (int i = 0; i < y; i++) {
cout << *(x + i) << "\n"; //printing ARR1
arr2[i] = x[i]; //assigning ARR1 values to ARR2
}
cout << "\n\n";
return arr2; //returning ARR2 to main()
}
int main() {
int arr1[] = {1,2,3,4,5};
int size = 5; //size of arr1
int *ans = copy(arr1 , size); //obtaining ARR2 from copy()
cout << "Printing ARR2 from MAIN() function\n";
for (int i = 0; i < size; i++) {
cout << *(ans+i) << "\n"; //trying to print arr2 but its giving incorrect output.
}
return 0;
}
OUTPUT
Printing ARR1
1
2
3
4
5
Printing ARR2 from MAIN() function
-858993460
0
-858993460
6026436
6027184
Press any key to continue . . .