使用指针进行基本整数交换
basic integer swap with pointers
我试图使用指针交换几个整数,但由于某种原因,我不完全理解发生了什么。
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];
假设p1
和p2
指向x
,y
你可以这样可视化它
你有你的三个变量
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
被切换了。
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- 在两个整数之间交换最右边的N位
- 使用指针交换整数
- 给定一个无符号整数,很容易交换每个偶数位和奇数位。这可以推广到交换每个偶数和奇数n位吗?
- 编写一个功能,该函数将使用框架交换两个整数
- 为什么它不交换数组中的两个整数?
- 为什么 a = (a+b) - (b=a) 是交换两个整数的糟糕选择
- 性能交换整数与双精度
- 通过单行中的XOR交换整数.在c++11中真的允许这样做吗
- 如何编写constexpr交换函数来更改整数的尾数
- 如何在C++从字节数组中提取字节时交换 64 位整数
- 使用指针进行基本整数交换
- 什么是用于交换2个整数变量的C代码
- 交换整数的第I位和第j位
- 如何使用原子增量和比较与交换操作处理整数溢出