我正在尝试使用指针交换一些整数,但出于某种原因,我并不完全理解发生了什么。
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
temp = *p2;
*p2 = *p1;
*p1 = temp;
cout<< "x: " << x <<endl;
cout<< "y: " << y <<endl;
我得到的输出是: ×:0 是:99 ×:0 是: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];
关于c++ - 带指针的基本整数交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19129252/