Search code examples
cmultidimensional-arraymallocdeep-copy

Deep copying array in C... malloc?


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...)?


Solution

  • 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));