1

I use this code:

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

with definition:

double** arr;           // arr1 is difined 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?

mja
  • 1,273
  • 1
  • 20
  • 22

3 Answers3

9

sizeof(arr1[i]) yields the size of a double* pointer variable, not the actual size of the array you have allocated.

That warning is perfect, appreciate it.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
8

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!

MNS
  • 1,354
  • 15
  • 26
2

Try sizeof(double) * col instead. sizeof() doesn't know what argument you passed to new.

Todd Christensen
  • 1,297
  • 8
  • 11