void do_something(int *array) {}
void do_something(int array[]) {}
void do_something(int array[5]) {}例如下面的 do_something() 印出陣列前 5 個元素值
#include <iostream>
void do_something(int n[]) {
for (int i = 0; i < 5; i++) {
std::cout << n[i] << std::endl;
}
}
int main(void)
{
int a[] = {1, 2, 3, 4, 5, 6, 7};
do_something(a);
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:fundemo07.cpp
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2013 年 1 月 */編譯執行結果如下

下面的 do_something2() 則重新設定陣列的前 5 個元素值
#include <iostream>
void do_something2(int n[]) {
for (int i = 0; i < 5; i++) {
n[i] = 0;
}
}
int main(void)
{
int a[] = {1, 2, 3, 4, 5, 6, 7};
do_something2(a);
for (int i = 0; i < 7; i++) {
std::cout << a[i] << std::endl;
}
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:fundemo08.cpp
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2013 年 1 月 */編譯執行結果如下

不過這樣的設計有個缺陷,就是沒有傳遞陣列大小的參數,有可能導致超出陣列索引值範圍的錯誤。因此保險一點的寫法是用另一個整數參數傳遞陣列大小,例如
void do_something(int array[], int n) {}| 中英文術語對照 | |
|---|---|
| 陣列 | array |
| 函數 | function |
| 參數 | parameter |
| 指標 | pointer |
您可以繼續參考
函數
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言