C++中利用子函数交换main()中的一个int数组的值,交换地址为什么不可?

某书思考题 只改动子函数 实现主函数中数组排序
我写了3种子函数 注释的都是可以正常用的 最上面的不可以(排序没变)
不知道是为啥
(指针不是代表地址吗 既然形参无法传回那我改变地址应该也可以啊)

 #include<iostream>
#include<iomanip>
#include<cstdlib>                //pause
using namespace std;

//排序不变
void swap(int x,int y)
{
    int *t1,*t2,*t3;
    t1=&x;
    t2=&y;
    t3=t1;
    t1=t2;
    t2=t3;
}

/*
void swap(int &x,int &y)
{
    int t;
    t=x;
    x=y;
    y=t;
}
*/
/*
void swap(int *x,int *y)
{
    int *t;
    t=x;
    x=y;
    y=t;
}
*/
void printa(int b[])
{
    int i;
    for(i=0;i<10;i++)
    {
        cout<<setw(5)<<b[i];
    }
    cout<<endl;
}

int main()
{
    int a[10]={10,21,62,96,57,81,44,31,72,35},i,j;
    int *p=a;
    cout<<"排序前:"<<endl;
    printa(a);

    cout<<p<<endl;
    cout<<&a[0]<<endl;             //a0地址的2种方法

    for(i=0;i<10;i++)
    {
        for(j=0;j<10-1;j++)
        {
            if(a[j]>a[j+1])
            {
                swap(a[j],a[j+1]);
            }
        }
    }
    cout<<"排序后:"<<endl;
    printa(a);
    system("pause");
    return 0;
}

swap(int x,int y),你这个函数是值传递,不是地址传递,函数里面的x变量是个临时的变量,你可以Debug看看函数内的x的地址,是不是你main函数里的a的地址。

你要i修改值,函数参数需要是指针,或者引用。

你交换的是x和y的地址,并不是数组元素的地址。而x和y是临时变量,函数执行完就释放了,意思你这样交换了两个无用的变量的地址,原来的数组动都没动

搞清楚值传递,指针传递,和引用就ok

swap(int x,int y),你这个函数是值传递,不是地址传递,函数里面的x变量是个临时的变量,你可以Debug看看函数内的x的地址,是不是你main函数里的a的地址。 初学者要好好理解值传递与引用传递