Search code examples
c++multidimensional-arraymemcpy

memcpy and two-dimensional arrays


I've been using memcpy for a while with one-dimensional arrays but when I try two-dimensional weird things happen. The following program illustrates the issue:

using namespace std;
#include <iostream>  
#include <string.h>
#include <complex>

int main() {

    int n=4;
    complex<double> **mat1=new complex<double>*[n], **mat2=new complex<double>*[n];
    for(int i=0;i<n;i++) {mat1[i]=new complex<double>[n]; mat2[i]=new complex<double>[n];}

    for(int i=0;i<n;i++) {
        for(int j=0;j<n;j++) mat1[i][j]=complex<double>(i*j, i+j);
    }

    cout << endl << "Matrix 1:" << endl;
    for(int i=0;i<n;i++) {
        for(int j=0;j<n;j++) cout << mat1[i][j] << "  ";
        cout << endl;
    }

    cout << endl << "memcpy" << endl << endl;
    memcpy(mat2, mat1, n*n*sizeof(complex<double>));

    cout << "Matrix 1:" << endl;
    for(int i=0;i<n;i++) {
        for(int j=0;j<n;j++) cout << mat1[i][j] << "  ";
        cout << endl;
    }

    cout << endl << "Matrix 2:" << endl;
    for(int i=0;i<n;i++) {
        for(int j=0;j<n;j++) cout << mat2[i][j] << "  ";
        cout << endl;
    }
}

The first printout of mat1 works fine but in the second and that of mat2 the first half of the elements are gibberish. Any idea what's going on?


Solution

  • You are not using the two dimensional arrays. You are using the 1 dimensional arrays and another one which is storing the set of pointers. Giving that there is no guarantee that your arrays will reside in the memory continuously.

    Every time you are asking in the code for new allocation your program will find a (new) memory region to fit in the (new) array. If you will print the array storing the pointers you can read where your arrays actually reside.