c++ - 从 C++ 中的函数更改数组

标签 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;
}

为什么 someFunction4() 不改变 main() 中的数组 y?当我在 main() 中调用另一个 someFunctionX() 时,y 成功地从 {0, 1, 2}{2, 1, 0}

最佳答案

someFunction4 中,您分配 x 以指向一个新的 整数数组,然后对其进行分配。您传递给函数的变量指向的数组仍然指向旧数组。旧数组保持不变,因为在 someFunction4 中您设置了 x 以引用不同的数组,即您通过 new 在函数中创建的数组>.

为了使 someFunction4() 中的原始 x 保留您分配的值,请执行以下两项操作之一:

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

在你的主要任务中,做

someFunction4(&y,3); 

关于c++ - 从 C++ 中的函数更改数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13295011/

相关文章:

C++ 引用不一致

c++ - 静态数组上的 memset

c++ - 数组结构

C++ 链表结构引用为双指针,需要访问下一个节点

Javascript 的数组反转

php - 合并两个多维数组

java - getRaster 方法中出现数组越界异常

python - 将循环中的数组保存在一个 txt 文件的列中

java - 如何将字节数组数据放入DoubleBuffer

c++ - 在 RVO 存在的情况下默认/删除移动构造函数和赋值