Search code examples
cpointersmatrixcopymemcpy

Isn't this code incorrect?


My instructor presents this slide for "matrix copying":

#define ROWSIZ 17
#define COLSIZ 27
int enamatrisen[ROWSIZ][COLSIZ];
int andramatrisen[ROWSIZ][COLSIZ];

void matcpy (int* dst, int* src)
{
  int i, j;
  for (i=0; i<ROWSIZ, i=i+1)   /* rad-nr */
   for (j=0; j<COLSIZ, j=j+1)  /* kolumn-nr */
    dst[i][j] = src[i][j];
}

But

1) There're bugs where it says , it should be ; and

2) The code doesn't compile. gcc complains about pointer being used as arrays or similar. What is correct code? How is this effort close? Shouldn't memcpy be used for this instead or is this an effort to implement something like memcpy?


Solution

  • The function parameters are defined wrong.

    More info on passing multi-dimentional arrays: http://www.eskimo.com/~scs/cclass/int/sx9a.html

    Also, comma in the for loop should be a semi-colon.

    void matcpy(int dst[][COLSIZ], int src[][COLSIZ])
    {
        int i, j;
        for (i = 0; i < ROWSIZ; i = i + 1)   /* rad-nr */
            for (j = 0; j < COLSIZ; j = j + 1)  /* kolumn-nr */
                dst[i][j] = src[i][j];
    }
    

    or

    void matcpy(int (*dst)[COLSIZ], int (*src)[COLSIZ])
    { 
        int i, j;
        for (i = 0; i < ROWSIZ; i = i + 1)   /* rad-nr */
           for (j = 0; j < COLSIZ; j = j + 1)  /* kolumn-nr */
               dst[i][j] = src[i][j];
    }