Copying multi char array to another multi char array

102 views Asked by At

I'm converting Java code to C, and something as simple as swapping contents of multi arrays in Java:

boolean[][] temp = board;
board = nextBoard;
nextBoard = temp;

Seems to be a lot more troublesome in C.

After viewing similar questions on this site, I have learned that I have to use memcpy which I initiated in a method called arrayCopy.

This is arrayCopy:

 void arrayCopy(char * a, char * b)
 {
     struct universe data;
     int r;
     for(r = 0; r < data.rows; r++)
     memcpy(b, a, sizeof(a));
 }

Which I call from the main method:

char temp[SIZE][SIZE];
arrayCopy(&data.board, &temp);
arrayCopy(&data.nextBoard, &data.board);
arrayCopy(&temp, &data.nextBoard);

With the following struct:

struct universe
{
  char board[SIZE][SIZE];
  char nextBoard[SIZE][SIZE];
  int columns;
  int rows;
}universe;

But I'm getting warnings such as:

A2Q1.c:189:15: warning: incompatible pointer types passing 'char (*)[60][60]' to parameter of type 'char *'

Yet memcpy only returns pointers, so I can't switch the parameters. I also can't use malloc() yet as other questions suggest because I have not learned it yet, so any other suggestions would be appreciated.

2

There are 2 answers

0
BLUEPIXY On BEST ANSWER

try this

void swapBoard(struct universe *x){
    char temp[SIZE][SIZE];
    memcpy(temp, x->board, sizeof(temp));
    memcpy(x->board, x->nextBoard, sizeof(temp));
    memcpy(x->nextBoard, temp, sizeof(temp));
}
int main(){
    struct universe data;
    //...
    swapBoard(&data);
0
Shawn Rakowski On

I think you are making it a bit over-complicated. You can use memcpy directly in your example above to copy everything from a to b without iterating through it. If you run this code...

int main()
{
    char temp[60][60];
    printf("%d", sizeof(temp));
}

You'll see that sizeof will give you 3600 bytes, 60*60 to the total bytes allocated by the array. These byte are allocated in a contiguous chunk of memory and memcpy can copy them in one swoop. This demonstrates the point:

int main()
{
    char temp[60][60];
    memset(temp, 'a', sizeof(temp));
    char temp2[60][60];
    memset(temp2, 'b', sizeof(temp2));
    memcpy(temp2, temp, sizeof(temp2));
    printf("%c", temp2[23][34]);
}

The printf will print 'a'. In your code above, this should work just fine:

char temp[SIZE][SIZE];
memcpy(data.board, temp, sizeof(data.board));
memcpy(data.nextBoard, data.board, sizeof(data.nextBoard));
memcpy(temp, data.nextBoard, sizeof(temp));

Note that this assumes all of these arrays are identical in size. You may want to create a minsize function or use a macro function like #define MINSIZE(a,b) (sizeof((a)) < sizeof((b)) ? sizeof((a)) : sizeof((b))) to be safe.