【day0403】C++ 數組形參的傳遞

# 數組是C/C++重要的一個知識點,C++的字符串又不同於c的字符數組(C風格字符串)

今天寫點代碼試試函數參數傳遞--數組形參

* 三種傳遞數組的寫法

* 數組實參:數組名--指向數組首地址的一個指針

* 通過引用傳遞數組

* 二維(多維)數組的傳遞


Demo1:

#include <iostream>

using namespace std;

/*數組形參*/

//傳入數組首地址,還需傳入數組長度
    /*以下兩個相同*/
//void print_1(const int x[], const size_t len);
//void print_1(const int x[10], const size_t len); //長度10沒有用
void print_1(const int *x, const size_t len)
{
    cout << "傳入數組首地址(指針):\n";

    for (size_t i = 0; i < len; ++i){
        cout << x[i] << ", ";
    }
}

//數組引用形參
void print_2(int (&x)[10])  //長度10必須寫
{
    cout << "\n\n數組引用形參:\n";

    for (size_t i = 0; i < 10; ++i){
        cout << x[i] << ", ";
    }
}

//C++標準庫的寫法
//傳入收地址和指向最後一個的下一個地址。
void print_3(int *bgn, int *end)
{
    cout << "\n\nC++標準庫的寫法:\n";

    while (bgn != end){
        cout << *bgn++ << ", ";
    }
}

/// 二維數組形參
/// 參數:*x表示數組的第0行,每行有10個元素;一共有row_size行
void print_4(int (*x)[10], int row_size)
{
    cout << "\n\n二維數組的形參:\n";

    for (int i = 0; i != row_size; ++i){
        for (int j = 0; j < 10; ++j){
            cout << x[i][j] << ", ";
        }
        cout << endl;
    }
}

/// C風格字符數組,最後一個字符是NULL
void print_ch(const char *arr)
{
    cout << "\n\nC風格字符數組:\n";

    while (*arr != NULL){
        cout << *arr++;
    }
}


int main()
{
    int arr[10] = {14,15,21,23,56,8,78,79,22,94};
    int arr2[][10] = {{14,15,21,23,56,8,78,79,22,94},
                      {15,21,23,56,8,78,79,22,94,1},
                      {21,23,56,8,78,79,22,94,22,33} };
    char *str = "Hello Love! Today is 0403.\n";

    print_1(arr, 10);

    print_2(arr);

    print_3(arr, arr+10);

    print_4(arr2, 3);

    print_ch(str);

    return 0;
}
輸出:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章