Anoml Anoml - 25 days ago 8
C Question

Passing and returning 2D arrays in C

I have not coded in C much at all so I am having difficulty's with pointers for a 2D array. I have a 2D array 3x3 of type integer.

Here is my method I am trying to use:

void addMoveToBoard(int *gameArray[3][3], int a, int b, int player) {
*((int *)gameArray + x * 3 + y) = player;
if (a == 0) {
mvaddch(a, b, 'X');
}
...
}


And here is my main:

int *board[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
addMoveToBoard(board, 0, 0, 1);


First issue is when I pass the zero's for the 2nd and 3rd parameters, they are not 0 when I use them in the function. When using mvaddch(a,b, 'X') it appears as though a and b are 1 instead of 0. Also am I correctly assigning a value to a element in game array?

Answer

Change your function signature to be without the *:

void addMoveToBoard(int gameArray[3][3], int a, int b, int player)

now just write:

gameArray[x][y] = player;

and in main:

int board[3][3] = {{0,0,0},{0,0,0},{0,0,0}};

The rest is OK. Important to know is that the compiler sees you using an array and passes it as a pointer to the function. The function receives a pointer to the board array and the compiler "knows what to do" when you index it as [x][y].