我是C ++的新手,并试图理解指针的应用以及传递和返回数组作为参数。
在此代码中,我有一个名为ARR1 的数组,作为参数传递给函数copy(),此函数打印ARR1 和< strong>创建ARR2 (ARR1的副本)返回到main()。
在main()内部功能我正在尝试打印arr2,但输出错误。
这是代码:
#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;
}
输出
Printing ARR1
1
2
3
4
5
Printing ARR2 from MAIN() function
-858993460
0
-858993460
6026436
6027184
Press any key to continue . . .