函數參數傳遞
傳參方式
- 值傳遞
- 址傳遞
- 若是想經過參數改變某一個變量的值,實參爲該變量的地址。稱爲址傳遞
- 引用傳遞
數組做爲函數的形參
- 弱化爲指針類型 大小爲4個字節
- 當數組做爲函數形參時,必須添加一個參數做爲數組大小
練習代碼
void change(int a, int b) {
int t = a;
a = b;
b = t;
cout << "a=" << a << endl;
cout << "b=" <<b << endl;
}
void change(int *pa, int *pb) {
int t = *pa;
*pa = *pb;
*pb = t;
cout << "a=" << *pa << endl;
cout << "b=" << *pb << endl;
}
void change1(int& a, int& b) {
int t = a;
a = b;
b = t;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
void GetMemory(int **p) {
*p = new int;
}
void PrintArray(int n[100],int size) {
cout <<sizeof(n) << endl;
for (int i = 0; i < size;i++)
{
cout << n[i] << endl;
}
}
int main() {
int n[6] = {};
PrintArray(n,6);
int *p = nullptr;
GetMemory(&p);
cout << p << endl;
delete p;
p = nullptr;
int a = 10, b = 20;
change(a, b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
change(&a, &b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
change1(a, b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
return 0;
}
複製代碼