我正在學習C++中針對即將到來的考試的指針,我不知道爲什麼這裏的第一個代碼不會交換值,但第二個代碼會這樣。如果有人能向我解釋爲什麼那會很好。爲什麼這個程序不能改變任何東西,但它下面的東西呢?
爲什麼不會這一計劃交換B [0]和b的值[1]:
#include <iostream>
using namespace std;
void func1 (int* x, int *y)
{
int* temp = x;
x = y;
y = temp;
}
int main()
{
int b[6] = { 1, 2, 3, 4, 5, 6};
func1(&b[0], &b[1]);
cout << b[0] << b[1];
}
但這一個作用:
#include <iostream>
using namespace std;
void func2(int* x, int *y)
{
int temp = *x;
*x = *b;
*y = temp;
}
int main()
{
int b[6] = { 1, 2, 3, 4, 5, 6};
func2(&b[0], &b[1]);
cout << b[0] << b[1];
}
謝謝:d
in func2,當你寫'b'時,你的意思是'y'嗎? –