# 传值与传地址

NO.1

void swap(int a, int b)

{

cout << "a = " << a << " b = " << b << endl;

int tmp = a; a = b; b = tmp;
cout << "a = " << a << " b = " << b << endl; }
int main() { int x = 1, y = 2;
cout << "x = " << x << " y = " << y << endl;
swap(x, y);
cout << "x = " << x << " y = " << y << endl;
return 0; }

NO.2

class Point

{

public:

int x;

int y;

};

void swap(Point pt) { cout << "pt.x " << pt.x << " pt.y " << pt.y << endl;
int tmp = pt.x; pt.x = pt.y; pt.y = tmp;
cout << "pt.x " << pt.x << " pt.y " << pt.y << endl; }
int main() { Point pt; pt.x = 1; pt.y = 2;
cout << "pt.x " << pt.x << " pt.y " << pt.y << endl; swap(pt); cout << "pt.x " << pt.x << " pt.y " << pt.y << endl;
return 0; }

NO.3

class Point

{

public:

int x;

int y;

};

void swap(Point *pt) { cout <x = " <x <y = " <y << endl;
int tmp = pt->x; pt->x = pt->y; pt->y = tmp;
cout <x = " <x <y = " <y << endl; }
int main() { Point *pt = new Point();
pt->x = 10; pt->y = 20;
cout <x = " <x <y = " <y << endl; swap(pt); cout <x = " <x <y = " <y << endl;
return 0; }

1、这里实参和形参保存了相同的堆地址，但是实参和形参的地址是不一样的，实参在栈中的地址是 0x0019fefc，形参在栈中的地址是 0x0019fe18。

2、栈地址的由 0x0019 开头的，而堆地址是由 0x004a 开头的，两块内存的跨度很大。
3、如果你在你的机器上进行调试的时候，你的栈地址、堆地址跟我可能会不一样，因为这些地址受操作系统版本号、补丁号、编译器版本、甚至编译器参数的影响。

NO.4

NO.5

void swap(int *a, int *b)

{

cout << "*a " << *a << " *b " << *b << endl;

int tmp = *a; *a = *b; *b = tmp;
cout << "*a " << *a << " *b " << *b << endl; }
int main() { int x = 1, y = 2;
cout << "x " << x << " y " << y << endl;
swap(&x, &y);
cout << "x " << x << " y " << y << endl;
return 0; }

NO.6
Java 传参
Java 中说的传参全部是传值，但是当形参是一个对象的时候，其实相当于传的是一个地址。因为变量中本身就保存的是一个地址，而不是一个值。具体方式和 C++ 的是类似的（和第三段代码类）。Java 的对象是 new 出来的，也在堆空间中，而 new 赋值的那个变量是在栈中，栈中同样保存的是堆空间的首地址。传参时，也是把堆空间的地址传给了形参。Java 的堆和栈，是由 JVM 管理和维护。