Search code examples
c++pointersc++11

C++: How to use memcpy with pointer **?


I use this code:

memcpy(arr[i], arr1[i], sizeof(arr1[i]));

with definition:

double** arr;           // arr1 is defined the same way.
arr = new double*[row];
for (int i = 0; i < row; ++i) {
    arr[i] = new double[col];
    memcpy(arr[i], arr1[i], sizeof(arr1[i]));
}

I built it with command : g++ -Wall -Wextra -Wpedantic -c arr.cpp and had result:

Warning: argument to 'sizeof' in 'void* memcpy(void*, const void*, size_t)' call is the same pointer type 'double*' as the destination; expected 'double' or an explicit length [-Wsizeof-pointer-memaccess]

memcpy(arr[i], arr1[i], sizeof(arr1[i]));

I don't understand what it is. Could you tell me how to make it work correctly?


Solution

  • A small visualization can help you to understand the warning better.

    enter image description here

    Suppose row = 2 and col = 2. Above picture shows visualization of arr1[0].

    In your code memcpy(arr[i], arr1[i], sizeof(arr1[i])); the sizeof(arr1[i]) yields size of double* (as indicated by @πάντα ῥεῖ). As seen in the above picture, arr1[0] is a pointer to double and hence sizeof(arr1[0]) can take a value of 4 or 8 depending upon whether you are running a 32 or 64 bit application.

    If col = 2 then arr1[0] can hold two double values, namely arr1[0][0] and arr1[0][1] as shown in the picture. Since you want to copy an entire row, you will have to specify the length of bytes held by arr1[0] which can be achieved by sizeof(double)*col as indicated by @ToddChristensen or by sizeof(arr1[i][0])*col.

    Since the warning you receive calls for the specification of an explicit length, you will have to use below memcpy in order for your copy operation to work correctly.

    memcpy(arr[i], arr1[i], sizeof(arr1[i][0])*col);
    

    Hope this help!