我试图使用指针交换一些整数,由于某种原因,我不完全理解发生了什么。
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
temp = *p2;
*p2 = *p1;
*p1 = temp;
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
我得到的输出是:x:0 y:99 x:0 y: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。其他一切都可以正常工作。
哦,我的上帝,没关系,这是阵列。非常感谢您发现那个愚蠢的错误。