通过引用数组值进行交换

Swapping by reference array values

本文关键字:交换 数组 引用      更新时间:2023-10-16

因此,在我执行此交换函数之后,数组中的所有值都将变为-858993460。为什么是这个数字?我想这是我声明数组的方式,但A这样声明不是指针吗?我想弄清楚为什么会这样。这是代码:

int* arrayCreate()//added mg
{
    int a[] = { 3, 7, 4, 9, 5, 2 };
    return a;
}
void Sort::Insert()
{   
    int t = 0;
    //start clock
    clock_t start = clock();
    d = arrayCreate();  
    size = 6;
    for (int i = 1; i< size; i++)
    {
        t = i;
        while (((t - 1) >= 0) && (d[t] < d[t- 1]))
        {
            //Swap
            Swap(d[t], d[t- 1]);  // right after this call 
                                  //the debugger says values go to - 8e^8
            t--;
        }
    }
}
void Sort::Swap(int& n1, int& n2)
{
    int temp = n1;
    n1 = n2;
    n2 = temp;
}

您忽略了所有基于堆栈的变量在退出其定义的范围后都会被销毁。

因此,一旦返回A,它就会指向未定义的内存。

int* arrayCreate()//added mg
{
    int a[] = { 3, 7, 4, 9, 5, 2 };
    return a;
}

可以更改为此

int* arrayCreate()//added mg
{
    static int a[] = { 3, 7, 4, 9, 5, 2 };
    return a;
}

将数组标记为静态会导致内存滞留。