我試圖用指針交換幾個整數,出於某些原因,我不完全理解發生了什麼。帶指針的基本整數交換
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 其他一切工作,因爲它應該。
噢,我的上帝永遠不知道它是陣列。非常感謝你捕捉到那個骨頭錯誤。
如何三個變量初始化? – pickypg
你能發佈完整的代碼嗎? – Pradheep