0
votes

I'm trying to make a deep copy of an array in C (originalBoard being the copy):

int gy, gx;          
            for (gy=0; gy<9; gy++)
            {
                for (gx=0; gx<9; gx++)
                {                  
                g.originalBoard[gy][gx]=g.board[gy][gx];
                }
            }

This does not seem to be working out, and I'm guessing this is just making pointers to the original board array.

So would the solution be to try and use malloc? Like:

    int* g.originalBoard[9][9]=malloc(sizeof(g.board[9][9]));

btw this is a 9x9 two dimensional array. What would the syntax be (the compiler gives an error for the above line...)?

3

3 Answers

3
votes

I think you need this:

 //assuming g.originalBoard is array of array of integers and same for g.board  
int *originalBoard = malloc(sizeof(g.board));
memcpy(originalBoard, g.board, sizeof(g.board));
0
votes

This is the correct place to use memcpy. You probably want

g.originalBoard = (int *)malloc(9 * 9 * sizeof(int));
if (NULL == g.originalBoard) {
    /* malloc failed, so handle the error somehow */
}
memcpy(g.originalBoard, g.board, 9 * 9 * sizeof(int));

You may notice that in the above solution you have to use g.board[r * 9 + c] to access the item at index (r, c), rather than two indices. This is because of the way this dynamically allocates memory - at compile-time g.board and g.originalBoard are just pointers, not arrays. Alternatively, if you have control over the definition of the type of g, you can hardcode the size of the matrix as

struct foo {
    int board[9][9];
    int originalBoard[9][9];
    /* Other fields here */
};

Then you wouldn't have to malloc extra space for g.board and g.originalBoard - those two fields would be automatically allocated whenever you allocated space for g itself. Also, you could use g.board[r][c] instead of g.board[r * 9 + c].

0
votes

By the way, if you are trying to execute the following 'intended' task on the arrays,

int* g.originalBoard[9][9]=malloc(sizeof(g.board[9][9]));

then you should change the above line to

int* g.originalBoard[8][8]=malloc(sizeof(g.board[8][8]));

because this is a 9x9 two dimensional array and in C arrays are ZERO-based.