MelMed Mido
MelMed Mido

Reputation: 1

Using memcpy for two dimensional dynamic array?

I am able to declare in a good way two matrices A and B.

But, when using the memcpy (to copy B from A), B gives me arrays of 0s.

How can I do? Is my code correct for using memcpy?

int r = 10, c = 10, i, j;

int (*MatrixA)[r];
MatrixA=malloc(c * sizeof(*MatrixA));
int (*MatrixB)[r];
MatrixB=malloc(c * sizeof(*MatrixB));

memcpy(MatrixB,MatrixA,c * sizeof(MatrixA));


for(i=1;i<r+1;i++)
{
     for (j = 1; j < c+1; j++)
    {
        MatrixA[i][j]=j;
         printf("A[%d][%d]= %d\t",i,j,MatrixA[i][j]);
    }
    printf("\n");
}
printf("\n");printf("\n");printf("\n");printf("\n");printf("\n");

for(i=1;i<r+1;i++)
{
     for (j = 1; j < c+1; j++)
    {
        printf("B[%d][%d]= %d\t",i,j,MatrixB[i][j]);
    }
    printf("\n");
}

Upvotes: 0

Views: 1004

Answers (2)

Marcus M&#252;ller
Marcus M&#252;ller

Reputation: 36337

Is my code correct for using memcpy?

No, your code is wrong, but that's less of a memcpy problem. You're simply doing C arrays wrong.

int r = 10, c = 10, i, j;

int (*MatrixA)[r];
MatrixA=malloc(c * sizeof(*MatrixA));

Ok, MatrixA is now a pointer to a 10-element array of integers right? So the compiler reserves memory for ten ints; however, in the malloc line, you overwrite that with a pointer to a memory region of ten times the size of a single integer. A code analysis tool will tell you that you've built a memory leak.

These mistakes continue throughout your code; you will have to understand the difference between statically allocated C arrays and dynamic allocation using malloc.

Upvotes: -2

ameyCU
ameyCU

Reputation: 16607

You copied contents before initializing MatrixA .And also you access index out of bound (r+1 evaluates 11 which is out of bound) causing UB. Do this instead -

for(i=0;i<r;i++)            //  i starts from 0 
{
    for (j =0; j < c; j++)         // j from 0
  {
       MatrixA[i][j]=j;
       printf("A[%d][%d]= %d\t",i,j,MatrixA[i][j]);
  }
   printf("\n");
}

memcpy(MatrixB,MatrixA,c * sizeof(*MatrixA));   // copy after setting MatrixA

for(i=0;i<r;i++)              // similarly indexing starts with 0
{
    for (j =0; j < c; j++)
  {
    printf("B[%d][%d]= %d\t",i,j,MatrixB[i][j]);
  }
  printf("\n");
}

Upvotes: 3

Related Questions