简体   繁体   中英

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?

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.

As other stated, you shouldn't use memcpy here.

But for the record, when doing a memcpy this way, your erasing the pointers in mat2, creating a leak, and your copying something way too big in mat2, f***ing up your memory. The correct memcpy way would be to memcpy independently each entry of mat1 in mat2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM