1

I wanted to copy the contents of a c array to that of another, and I realized that you cant simply do

array1 = array2;

instead, you should either use a for loop to iterate over every index, or memcpy. I wanted to use memcpy as people said it would save space and I have a 3KB limit for my program (I want to fit it in a QR code).

I have a function where in my program where I have tried to utilize this, but when I print the results they come out as pointers. I am very confused as to why this is happening, because other people I've seen use this it turns out fine. What could i do instead? My function is here:

void ShiftBlock(int curBlock[4][2], int shiftCoords[2], int curGrid[WIDTH][HEIGHT])
{
     int blockCoords[4][2] = {0};
     memcpy(blockCoords, curBlock, sizeof(blockCoords));

     for(int i = 0; i < 4; i++)
     {
          blockCoords[i][0] += shiftCoords[0];
          blockCoords[i][1] += shiftCoords[1];

          if (0 > blockCoords[i][0] || blockCoords[i][0] > WIDTH || 0 > blockCoords[i][1] || blockCoords[i][1] > HEIGHT || curGrid[blockCoords[i][0]][blockCoords[i][1]] != 0)
          {
               return;
          }
     }

     memcpy(curBlock, blockCoords, sizeof(curBlock));
}
TryingMyBest
  • 63
  • 10

1 Answers1

1

Arrays can't be passed as parameters so for a parameter type the first dimension of an array type is always ignored and the parameter declaration is a pointer instead. So your function type is actually:

void ShiftBlock(int (*curBlock)[2], int* shiftCoords, int (*curGrid)[HEIGHT])

I recommend to use this form because the other one is misleading.

Now you can see that sizeof(curBlock) is wrong. It's just the size of a pointer. So either use sizeof(blockCoords) or sizeof(int[4][2]) or 4 * sizeof(*curBlock).

bolov
  • 72,283
  • 15
  • 145
  • 224