为什么数组变量被更新

 收藏

I wrote this code and a part of this is not written by me and I'm not able to understand how a function is updating my arrayData?

#include <iostream>
using namespace std;

int *insert(int arr[], int size, int elem, int pos);

int main()
{
    // Create a array
    int arrayData[50] = {0};

    // Insert data
    for (int i = 0; i < 10; i++)
    {
        arrayData[i] = i + 1;
    }

    int elem = 40, pos = 5, size = 10;

    // insert the element
    insert(arrayData, size, elem, pos);

    // show the data
    for (int i = 0; i < size + 1; i++)
    {
        cout << arrayData[i] << " ";
    }

    return 0;
}

int *insert(int arr[], int size, int elem, int pos)
{
    size++;

    // shift elements forward
    for (int i = size; i >= pos; i--)
        arr[i] = arr[i - 1];

    // insert x at pos
    arr[pos - 1] = elem;

    return arr;
}

OUTPUT: 1 2 3 4 40 5 6 7 8 9 10

回复
  • 云想衣裳 回复

    It is updating it because you are giving the function the memory address of the array (int arr[]), so the array is not copied into the function like other variables are.