watty
watty

Reputation: 83

When printing out double dimensional array to console, values are being set randomly

Let's say I create a double dimensional array in main fuction:

int board[8][8] = {0};

When I am printing it out to console with a simple FOR LOOP in MAIN everything works fine and console shows that all elements have been set to 0.

However, when I am trying to pass this array as an argument to the print function like shown below, some elements are set correctly to 0, whereas the rest become random values :

void print_board (int (*array)[8][8]);

int main (){

    int board[8][8] = {0};
    print_board(&board);

return 0;
} 

void print_board (int (*array)[8][8]){
    for (int i = 0; i < 8; i++){
        for (int j = 0; j < 8; j++){
            cout << *array[i][j] << " ";
        }
        cout << endl;
    }
}

I played with pointers and ampersands, and tried to google, but guess I am missing something.

Would be very grateful for your help!

Upvotes: 2

Views: 54

Answers (2)

songyuanyao
songyuanyao

Reputation: 172984

According to the Operator Precedence, operator[] has higher precedence than operator*. So *array[i][j] is equivalent to *(array[i][j]). And array is a pointer (to array), and array[i] might cause UB when i >= 1.

You should change it to

cout << (*array)[i][j] << " ";

Upvotes: 3

coincoin
coincoin

Reputation: 4685

You can change your output to std::cout << (*array)[i][j] or make things simpler:

void print_board(int array[8][8]){
    for (int i = 0; i < 8; i++){
        for (int j = 0; j < 8; j++){
            std::cout << array[i][j] << " ";
        }
        std::cout << std::endl;
    }
}


int main (){
    int board[8][8] = {0};
    print_board(board);
} 

Upvotes: 1

Related Questions