[英]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;
我得到的輸出是: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。其他所有操作均應正常進行。
哦,我的上帝沒關系,那是陣列。 非常感謝您發現了該錯誤。
這真是個壞消息:
int a[1];
您需要2個元素,而不是1個元素。正如您當前定義的那樣,在a[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
已切換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.