Search code examples
arrayscpointersimplicit-conversion

point to 2D array using double pointer


Here is code :

void nextGeneration(int **board) {

int editBoard[row][col];
    ...
    displayBoard(editBoard);
}

void displayBoard(int **board) {
    ...
}

I get this error msg:

GOL.c: In function ‘nextGeneration’: GOL.c:64: warning: passing argument 1 of ‘displayBoard’ from incompatible pointer type GOL.c:28: note: expected ‘int **’ but argument is of type ‘int (*)[(long unsigned int)(col)]’

I just don't know how to point 2D array that will be accepted to void displayBoard(int **board) function.

How can I do that?

Thank you very much


Solution

  • A double pointer is not a 2D array, but you can do it using a single pointer

    #include <stdio.h>
    
    #define COL_WIDTH 2
    
    int displayBoard(int *board, int row, int col)
    {
        // editBoard[row][col]
        return board[(COL_WIDTH*row)+col];
    }
    
    int main(void)
    {
        int board[2][COL_WIDTH] = { {1,2}, {3,4} };
    
        printf("%d\n", displayBoard((int *)(board), 1, 1));
        printf("%d\n", displayBoard((int *)(board), 0, 1));
    }