天天看點

【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;
}
           

輸出:

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

繼續閱讀