从函数中改变数组元素的值

jok*_*ker 11 c++ arrays

我是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;
}
Run Code Online (Sandbox Code Playgroud)

我认为带有注释的代码解释了问题所在,但是这里有更多信息:有4个函数,即someFunction,someFunction2,someFunction3,someFunction4.有一个数组y,其值为0,1,2.所有函数都会更改原始数组的值.也就是说,someFunctionX调用之后main函数中的y元素比调用函数之前的元素更改.

我的问题是:为什么someFunction4是唯一不改变值的函数?

提前致谢.抱歉我的英语不好

Gra*_*her 7

someFunction4,您指定x指向一个new整数数组,然后分配.传递给函数的变量指向的数组仍然指向旧数组.旧数组保持不变,因为someFunction4您已设置x引用不同的数组,即您在函数中创建的数组new.

为了使原来xsomeFunction4()保持你赋的值,做两件事情之一:

1)摆脱x = new int[n];.这将使someFunction4()之前的工作.

2)将指针x作为参数传递给someFunction4()someFunction4()使用指针.

int someFunction4(int *x[], int n)
{
    *x = new int[n];
    (*x)[0] = 2;
    (*x)[1] = 1;
    (*x)[2] = 0;
    return 0;
} // Makes x point to a new a new array
Run Code Online (Sandbox Code Playgroud)

在你的主要,做

someFunction4(&y,3); 
Run Code Online (Sandbox Code Playgroud)


kev*_*sco 5

在每一个someFunction,someFunction2someFunction3,你实际上是传递一个指针,以你在你的阵列分配的内存main().这意味着当您对数据进行操作时,此指针指向:

x[1] = 1;
Run Code Online (Sandbox Code Playgroud)

它实际上影响了y指向的内存main()!

但是,在中someFunction4,您使用以下语句重新指定指向x新内存的指针:

x = new int[n];
Run Code Online (Sandbox Code Playgroud)

因此它不再指向相同的内存,y并且在main()此之后对其进行的任何更改(但仅在someFunction4!的范围内)不会影响y.