我是 C++ 新手(每个新手 XD 的常规介绍),我发现了这种意外行为。我跟踪了程序中的变量和数组,直到确定了这种模式:
#include <iostream>
using namespace std;
void showArray(int arr[], int n)
{
for(int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
}
void someFunction(int x[], int n) // changes the original values
{
x[0] = 2;
x[1] = 1;
x[2] = 0;
}
void someFunction2(int * x, int n)
{
x[0] = 2;
x[1] = 1;
x[2] = 0;
} // changes the original values
int someFunction3(int x[], int n)
{
x[0] = 2;
x[1] = 1;
x[2] = 0;
return 0;
} // changes the original values
int someFunction4(int x[], int n)
{
x = new int[n];
x[0] = 2;
x[1] = 1;
x[2] = 0;
return 0;
} // does NOT change the original value
int main(void)
{
int * y = new int[3];
y[0] = 0;
y[1] = 1;
y[2] = 2;
showArray(y, 3);
someFunction4(y, 3);
showArray(y, 3);
return 0;
}
为什么不someFunction4()
改变y
数组main()
?当我改为调用另一个someFunctionX()
时,成功地从 更改为。main()
y
{0, 1, 2}
{2, 1, 0}