polishusar
polishusar

Reputation: 31

How to copy a matrix?

I need copy a matrix that I have set up as M into a new matrix M2 and output that matrix.

How can this be done?

Here's what I tried so far:

#include <iostream>

using namespace std;
#define N 24
void copy(int M[][N], int M2[][N], int ROWS, int COLS)
{
    int r, c;
    M2[r][c]= M[r][c];
    cout<< M2[r][c];
}

void print(int M[][N], int ROWS, int COLS)
{
    int r, c, row, col;
    row= 1;
    col= 1;
    M[row][col] = 2;
    for(r=0; r< ROWS; r++)
    {
        for(c=0; c < COLS; c++)
        {
            if(M[r][c]==0)
            {
                cout<<" ";
            }
            else if (M[r][c]==1)
            {
                cout<< "T";
            }
            else if (M[r][c]==2)
            {
                cout<< "*";
            }
            else
            {
                cout << M[r][c];
            }
        }

        cout <<endl; 
    }
}

void fill(int M[][N], int ROWS, int COLS, int row, int col)
{
    int r, c;    
    for(r=0; r< ROWS; r++)
    {
        for(c=0; c < COLS; c++)
        {
            if (r == 0 || r == ROWS - 1) {
                M[r][c]=0;
            }
            else if(c == 0 || c == COLS -1) {
                M[r][c]=0;
            }
            else {
                M[r][c]= 1;  
            }
        }
    }
}

int main()
{
    int M[N/2][N];
    int M2[N/2][N];
    int ROWS, COLS;
    int r, c;
    ROWS = sizeof(M) / sizeof(M[0]);
    COLS = sizeof(M[0]) / sizeof(M[0][0]);
    fill(M, ROWS, COLS, 1, 1);
    print(M, ROWS, COLS);
    copy(M, M2, ROWS, COLS);

    return 0; 
}

Upvotes: 0

Views: 413

Answers (2)

2to1mux
2to1mux

Reputation: 783

Since you are using two dimensional arrays to store the matrices, the copy of one into the other should be as simple as one call to memcpy. The contents of any array (regardless of dimension) are stored contiguously in memory.

In your copy function, just place the following line of code inside:

memcpy(M2, M1, r * c * sizeof(int));

Before the memcpy, make sure you have the appropriate values assigned to r and c (obviously this should be the correct number of rows and correct number of columns).

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283961

Here is a problem:

int r, c;
M2[r][c]= M[r][c];

You never assigned r and c, they contain some unknown value, which might well be outside the range 0..ROWS-1 and 0..COLS-1.

Don't use uninitialized values, especially in pointer arithmetic.

To copy the entire matrix, you will probably need some loops like you have in the print function.

Upvotes: 2

Related Questions