使用指针进行基本整数交换

basic integer swap with pointers

本文关键字:整数 交换 指针      更新时间:2023-10-16

我试图使用指针交换几个整数,但由于某种原因,我不完全理解发生了什么。

cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
temp = *p2;
*p2 = *p1;
*p1 = temp; 
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;

im 得到的输出是:x: 0Y: 99x: 0y: 0

谢谢

编辑:这就是我认为有问题的领域。整个代码是一系列指针任务。

#include <iostream>
using namespace std;
void swap(int *x, int *y);
void noNegatives(int *x);
int main ()
{
int x,y,temp;
int *p1, *p2;
p1 = &x;
*p1 = 99;
cout << "x: " << x << endl;
cout << "p1: " << *p1 << endl;
p1 = &y;
*p1 = -300;
p2 = &x;
temp = *p1;  
*p1 = *p2;
*p2 = temp;
noNegatives(&x);
noNegatives(&y);
p2=&x;
cout<< "x: "<<*p2<<endl;
p2=&y;
cout<< "y: "<<*p2<<endl;
int a[1];  
p2 = &a[0];
*p2 = x;
cout << "First Element: " << p2<< endl;
p2 = &a[1];
*p2 = y;
cout << "Second Element: " << p2<< endl;
p1 = &a[0];
p2 = &a[1];
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
temp = *p2;
*p2 = *p1;
*p1 = temp;
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
cout << "First Element: " << a[0]<< endl;
cout << "Second Element: " << a[1]<< endl;
swap(&x,&y);
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;

swap(&a[0], &a[1]);
cout<< "a[0]: " << a[0] <<endl;
cout<< "a[1]: " << a[1] <<endl;
}
void noNegatives(int *x)
{
    if(*x<0)
            *x=0;
}
void swap(int *p1, int *p2)
{
    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

我的目标是使最后一个 x 和 y 为 x:99 和 y:0。其他一切都按预期工作。

哦,天哪,没关系是阵列。非常感谢您发现那个愚蠢的错误。

这是个坏消息:

int a[1];

你想要 2 个元素,而不是 1 个。 正如您当前定义的那样,在 a[1] 处读取或写入已经过了数组的末尾,并且将具有未定义的行为。

这样做:

int a[2];
// etc...
p1 = &a[0];
p2 = &a[1];

假设p1p2指向xy你可以这样可视化它

你有你的三个变量

           temp [ ]
    *p1 [ x ]        *p2 [ y ]

我们想切换*p1*p2首先我们这样做

temp = *p2
           temp [ y ]
                  ^
                  |________
                            
    *p1 [ x ]          *p2 [ y ]

然后

*p2 = *p1
               temp [ y ]
     *p1 [ x ] ----------> *p2 [ x ]

然后

*p1 = temp
               temp [ y ]
                     /
          /----------
          V
    *p1 [ y ]                  *p2 [ x ]

现在你看到*p1*p2被切换了。