1

Why a 2-d address of following boolean "mat" can not be passed like this to a function?

void generate(bool arr) {
    ......;
    ......;
}

int main() {
    bool mat[3][3];
    generate(mat);
    return 0;
}
  • This is not a boolean. But a 2D boolean array. – Gimhani Sep 05 '18 at 05:26
  • Yeah I was uncertain about the code, but the question title and description seems to ask about passing a 2d array to a function so I figure this should hopefully answer OP's question regardless of their code – Tas Sep 05 '18 at 05:28
  • @user4581301, the "mat[3]mat[3]" was a typo. I fixed it. – marineCoder Sep 05 '18 at 08:55

1 Answers1

0

Try following example then attention to bellow descriptions :

const int N = 3;

void generate(bool arr[][N]) {
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            std::cout << std::boolalpha << arr[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    // initialize array
    bool mat[N][N] = { {1, 0, 1},
                     {0, 1, 0},
                     {1, 0, 1} };
    generate(mat);
    return 0;
}

The output :

true false true
false true false
true false true

Notice : There are 3 ways to pass a 2-d array to a function exactly according (this answer) :

  1. The function parameter is a 2-d array :

    bool arr[10][10];
    void Func(bool a[][10])
    {
        // ...
    }
    Func(arr);
    
  2. The function parameter is a array of pointers :

    bool *arr[10];
    for(int i = 0;i < 10;i++)
        arr[i] = new bool[10];
    void Func(bool *a[10])
    {
        // ...
    }
    Func(arr);
    
  3. The function parameters is as pointer to pointer :

    bool **arr;
    arr = new bool *[10];
    for(int i = 0;i < 10;i++)
        arr[i] = new bool[10];
    void Func(bool **a)
    {
        // ...
    }
    Func(arr);